2

I am trying to fetch entity which looks like this:

@Entity
public class Product{

  @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, orphanRemoval = true)
  private List<ProductVersion> versions;

}

But I also have to iterate through versions and then through some objects inside:

@Entity
public class ProductVersion{ 

   @ManyToOne
   @JoinColumn(name = "PRODUCT_ID", nullable = false)
   private Offer offer;

   @OneToMany(mappedBy = "productVersion", cascade = CascadeType.ALL)
   private Set<Objects> objects;

}

And because of that I need to have a query which would fetch Eagerly versions and objects inside versions (to avoid N+1 problem). Unfortunatelly because versions are inside of a List, query produces dupplicates (and unfortunatelly it has to be a List). Result look somewhat like this:

Product1{
    version1,
    version1,
    version1,
    version2,
    version2,
    version2
}
Product2{
        version1,
        version1,
        version1,
        version2,
        version2,
        version2
    }

EDIT: My current query looks somewhat like this (I am using JPAQuery):

QProduct qof = QProduct.product;
QProductVersion qProductVersionAlias = new QProductVersion("qProductVersionAlias ");
JPAQuery query = new JPAQuery(entityManager)
                .distinct()
                .from(qof)
                .join(qof.versions, qProductVersionAlias ).fetch()
                .leftJoin(qOfferVersionAlias.objects).fetch();

I have already found that in Criteria Api you could solve this problem like this:

criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);  

However I am searching for a JPA solution. So my question is how to solve this using JPA?

Rae Burawes
  • 892
  • 7
  • 18
pokemzok
  • 1,659
  • 1
  • 19
  • 29

0 Answers0