Issue
I have 2 tables (for this example, Customer and Product) to have json returned in a query, containing one field that is a list (one to many relationship)
public class Customer {
@Id
private Long id;
private String name;
@OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
private List<Product> products;
}
The hibernate query is very complicated and uses createNativeQuery()
For a rest api returning a single Customer, I simply run a second query for the products and set the field independently
customerDTO.setProduct(productsForCustomer);
But now I am requested to build an API that returns a list of ALL customers given certain criteria - must return List<Customer>
Is this even possible using nativeQuery or would I have to rewrite the query for entities using JQL?
Solution
Recommended approach would be JPQL. With a native query you would have to populate the entities by processing the resultset.
I guess it depends whether your complex query is whether it's possible with JPQL
In it's simplest form that would be
em.createQuery("select c from Customer c join fetch c.products where c.id = :id", Customer.class).setParameter("id", id).getResultList();
Answered By - johnnyutts
Answer Checked By - Mildred Charles (JavaFixing Admin)