hocikto
hocikto

Reputation: 981

JPA CriteriaBuilder JOIN not working for collection

I have two entities, in one to many relationship. I am trying to join the collection of entities, but can't wrap my head around it how to use the framework. I always used hibernate's DetachedCriteria but is not an option for me anymore, any help would be great.

@Entity
@Table(name = "Project")
public class Project implements Serializable {
....
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "project")
    private Collection<WorkReport> workReportCollection;
....


@Data
@Entity
@Table(name = "work_report")
public class WorkReport implements Serializable {
    @JoinColumn(name = "id_work_report", referencedColumnName = "id_work_report", insertable = false, updatable = false)
    @ManyToOne(optional = false)
    private Project project;

And I am trying to join workReportCollection like this, but it always throws

LazyInit Exception

when accessing the field.

CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<Project> query = builder.createQuery(Project.class);
        Root<Project> project = query.from(Project.class);
        Predicate idPredicate = builder.equal(project.get("idProject"), idProject);
        project.joinCollection("workReportCollection",  JoinType.LEFT);
        query.where(idPredicate);
        TypedQuery<Project> q = em.createQuery(query);
        return q.getSingleResult();

Only thing that works is using fetch instead of join but it fetches all other associations as well and that is too much data.

How to write a join correctly with JPA CriteriaBuilder? OR Should I use a fetch with some projection?

Upvotes: 0

Views: 1227

Answers (1)

Simon Martinelli
Simon Martinelli

Reputation: 36133

The join is correct but the collection is not initialized when you access it that's why you get the LazyInitException.

You have to add fetch:

project.fetch("workReportCollection");

to advice JPA to initialize the collection after querying.

Upvotes: 1

Related Questions