2017-07-18 97 views
6

我有一个客户实体,我只想从中选择几个字段及其关联的CustomerAddresses。我定义了一个Spring数据JPA投影界面如下:JPA的预测可以包含集合吗?

public interface CustomerWithAddresses { 
    Integer getId(); 
    String getFirstName(); 
    String getLastName(); 
    String getBrandCode(); 
    String getCustomerNumber(); 
    Set<CustomerAddress> getCustomerAddresses(); 
} 

但是从我的仓库方法:

CustomerWithAddresses findCustomerWithAddressesById(@Param("id") Integer id); 

我不断收到NonUniqueResultException与多个CustomerAddresses客户。投影是否必须有一个扁平的结构,即它们不像真实体一样支持集合?

回答

0

你有Set<CustomerAddress> getCustomerAddresses();这是X对多关系。当弹簧数据为CustomerWithAddresses选择时,它会加入结果集N记录(N - CustomerWithAddresses的CustomerAddress的数量为id = id)。您可以检查您是否将CustomerWithAddresses更改为CustomerWithAddresses列表。

List<CustomerWithAddresses> findCustomerWithAddressesById(@Param("id") Integer id); 

当您使用实体消费满数据gropu乘法结果到一个元素,它gouped由ID为ID是唯一的标识符。

你可以这样做:

1)添加到CustomerWithAddresses接口

@Value("#{target.id}") 
Integer getId(); 

,并使用您的查询

2)使用@Query

@Query("select adr from CustomerWithAddressesEntity adr where adr.id=:id") 
CustomerWithAddresses findCustomerWithAddressesById(@Param("id") Integer id);