Spring Data在@Query的select子句中使用参数

时间:2017-07-22 18:35:53

标签: java jpa spring-data

目标

我正在尝试定义一个通用查询,该查询允许我列出实体的属性(可能是嵌套的)的可能(不同)值。目标是在筛选实体列表时为最终用户选择一个下拉选项。

设置

@Entity
public class Customer {
  @Id @GeneratedValue Long id;
  @NotNull String name;
  @Embedded @NotNull Address address;
  ...
}

@Embeddable
public class Address {
  String country;
  String city;
  String postalCode;
  String street;
  String number;
  ...
}

public interface CustomRepository {
  @Query("select distinct ?1 from #{#entityName}")
  List<String> findAllValues(String value);

  @Query("select distinct ?1.?2 from #{#entityName} where ?1 IS NOT NULL")
  List<String> findAllSubValues(String path, String value);
}

public interface RepositoryCustomer extends
    CrudRepository<Customer, Long>,
    JpaSpecificationExecutor<Customer>,
    CustomRepository {}

用法

然后可以按如下方式使用该查询来显示一个选择框,用于根据客户列表的地址国家对其进行过滤:

public class SelectionComponent {
  @Autowired RepositoryCustomer repo;    
  ComboBox<String> select = new ComboBox<String>();

  @PostConstruct
  void onPostConstruct() {
    select.setItems(repo.findAllSubValues("address", "country"));
  }
}

问题

编译上述设置会产生以下异常:

org.hibernate.QueryException: Parameters are only supported in SELECT clauses when used as part of a INSERT INTO DML statement

问题

似乎不支持此功能。还有其他建议吗?

1 个答案:

答案 0 :(得分:0)

不要让此问题无解。通常,我的解决方案是避免涉及JPA和Spring数据时尝试表达关系或复杂查询。

我开始更喜欢为此类需求创建特定的(单一用途)数据库视图,并在我的“业务层”中进行非常简单的查询。从某种意义上讲,这会在数据库层中造成重复或非规范化,但大大降低了诸如JPA和Spring数据之类的覆盖框架所需的复杂性。

在这种情况下,我将拥有一个客户国家/地区数据库视图,该视图将映射到JPA实体。