[英]Spring Data use parameters in select clause of @Query
我正在尝试定义一个通用查询,它允许我列出实体的可能嵌套的属性的可能(不同)值。 目标是在过滤实体列表时为最终用户提供一个下拉选择。
@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
好像不支持这个。 任何替代建议?
不要让这个悬而未决。 我的解决方案通常是避免在涉及 JPA 和 Spring 数据时尝试表达关系或复杂查询。
我开始更喜欢为此类需求创建特定的(单一目的)数据库视图,并且在我的“业务层”中有一个非常简单的查询。 从某种意义上说,这会在数据库层创建重复或非规范化,但大大降低了覆盖框架(如 JPA 和 Spring 数据)所需的复杂性。
在这种特殊情况下,我将有一个客户国家/地区数据库视图,我将其映射到 JPA 实体。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.