简体   繁体   English

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

[英]Spring Data use parameters in select clause of @Query

Goal目标

I am trying to define a generic query that allows me to list the possible (distinct) values of a property, possibly nested, of an entity.我正在尝试定义一个通用查询,它允许我列出实体的可能嵌套的属性的可能(不同)值。 The goal is to have a drop down selection for the end user to choose from when filtering down the list of entities.目标是在过滤实体列表时为最终用户提供一个下拉选择。

Setup设置

@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 {}

Usage用法

The query could then be used as follows to show a selection box for filtering down the customers list based on their address country:然后可以按如下方式使用查询来显示一个选择框,用于根据客户的地址国家筛选客户列表:

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

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

Problem问题

Compiling the above setup results in follow exception:编译上述设置导致以下异常:

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

Question问题

It seems this is not supported.好像不支持这个。 Any alternative suggestions?任何替代建议?

To not leave this unanswered.不要让这个悬而未决。 My solution in general has been to avoid trying to express relational or complex queries when it comes to JPA and Spring data.我的解决方案通常是避免在涉及 JPA 和 Spring 数据时尝试表达关系或复杂查询。

I have come to prefer creating specific (single purpose) database views for such needs and have a very simple query in my "business layer".我开始更喜欢为此类需求创建特定的(单一目的)数据库视图,并且在我的“业务层”中有一个非常简单的查询。 In some sense, this creates duplication or denormalization in the database layer, but greatly reduces the complexity required from overlay frameworks such as JPA and Spring data.从某种意义上说,这会在数据库层创建重复或非规范化,但大大降低了覆盖框架(如 JPA 和 Spring 数据)所需的复杂性。

In this particular case, I would have a customer country database view that I would map to a JPA entity.在这种特殊情况下,我将有一个客户国家/地区数据库视图,我将其映射到 JPA 实体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM