问题描述
我有一个 Customer 实体,我只想从中选择几个字段及其关联的 CustomerAddresses.我已经定义了一个 Spring Data JPA 投影接口如下:
I have a Customer entity from which I only want to select a few fields and their associated CustomerAddresses. I've defined a Spring Data JPA projection interface as follows:
public interface CustomerWithAddresses {
Integer getId();
String getFirstName();
String getLastName();
String getBrandCode();
String getCustomerNumber();
Set<CustomerAddress> getCustomerAddresses();
}
但是从我的 Repository 方法:
But from my Repository method:
CustomerWithAddresses findCustomerWithAddressesById(@Param("id") Integer id);
对于具有多个 CustomerAddress 的客户,我不断收到 NonUniqueResultException.投影是否必须具有扁平结构,即它们不像真正的实体那样支持集合?
I keep getting NonUniqueResultException for Customers with multiple CustomerAddresses. Do projections have to have a flat structure, i.e. they don't support Collections the same way true Entities do?
推荐答案
you have SetgetCustomerAddresses();
它是 X 对多的关系.当 spring 数据确实为 CustomerWithAddresses 选择时,它确实加入了结果集中的 N 条记录(N - 为 CustomerWithAddresses 的 CustomerAddress 数量,id = id).您可以检查是否将 CustomerWithAddresses 更改为 List of CustomerWithAddresses .
you have Set<CustomerAddress> getCustomerAddresses();
it's X-to-Many relation. When spring data do select for CustomerWithAddresses it does join , in result set N-records (N - amount of CustomerAddress for CustomerWithAddresses with id = id). You can check if it you change CustomerWithAddresses to List of CustomerWithAddresses .
List<CustomerWithAddresses> findCustomerWithAddressesById(@Param("id") Integer id);
当您使用实体 sping 数据 gropu 将结果乘以一个元素时,将其按 id 排列为 id,这是唯一标识符.
when you use entity sping data gropu multiply result into one element , gouped it by id as id it's unique identifier.
你可以这样做:
1) 添加到 CustomerWithAddresses 接口中
1) add into CustomerWithAddresses interface
@Value("#{target.id}")
Integer getId();
并使用您的查询
2) 使用@Query
2) use @Query
@Query("select adr from CustomerWithAddressesEntity adr where adr.id=:id")
CustomerWithAddresses findCustomerWithAddressesById(@Param("id") Integer id);
这篇关于Spring JPA 投影可以有集合吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!