Can Spring JPA projections have Collections?

折月煮酒 提交于 2019-12-10 12:39:19

问题


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();
}

But from my Repository method:

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

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?


回答1:


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);

when you use entity sping data gropu multiply result into one element , gouped it by id as id it's unique identifier.

you can do :

1) add into CustomerWithAddresses interface

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

and use your query

2) use @Query

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


来源:https://stackoverflow.com/questions/45170258/can-spring-jpa-projections-have-collections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!