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?
Overview. When using Spring Data JPA to implement the persistence layer, the repository typically returns one or more instances of the root class. However, more often than not, we don't need all the properties of the returned objects. In such cases, we might want to retrieve data as objects of customized types.
Fetching a one-to-many DTO projection with JPA and Hibernate. The postDTOMap is where we are going to store all PostDTO entities that, in the end, will be returned by the query execution. The reason we are using the postDTOMap is that the parent rows are duplicated in the SQL query result set for each child record.
Spring data REST Projection supports projecting only a selected fields from an entity representation. To do that, we can define those specific fields into our @Projection interface. Let's create a custom view of our Student entity with first name and last name fields.
There is always confusion between JPA and Spring Data JPA. Spring Data JPA is an abstraction that makes it easier to work with a JPA provider like Hibernate which is used by default. Specifically, Spring Data JPA provides a set of interfaces for easily creating data access repositories.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With