简体   繁体   中英

How can I use Hibernate to load a list of entities and a subset of those entities' related entities?

I have a query I'd like to run against a table, let's call it parent where I'm grabbing all rows that match a certain criteria. In SQL:

select * from parent where status = 'COMPLETE';

I have this table and another related table ( child ) defined as Hibernate entities such that:

@Entity
@Table(name = "parent")
public class Parent {
    //...
    @OneToMany(mappedBy = "parent")
    private Set<Child> children;
    //...
}

@Entity
@Table(name = "child")
public class Child {
    //...
    @ManyToOne
    @JoinColumn(name = "parent_id")
    private Parent parent;

    @Column(name = "key")
    private String key;
    //...
}

I'd like my query to ALSO pull two optional child records where key is one of two values. So, in SQL:

select *
from parent p, child ca, child cb
where p.status = 'COMPLETED'
and p.id *= ca.parent_id
and ca.key = 'FIRST_KEY'
and p.id *= cb.parent_id
and cb.key = 'SECOND_KEY';

I could do this in Hibernate by just grabbing the result from the first query and iterating over the children collection looking for the rows I want but that's terribly inefficient: one query that does two outer joins vs one query + an additional query for each looking for the children I care about.

Is there a way to replicate the outer joins in the query above in Hibernate where the objects returned will have the children collection only populated with the two (or less, since they are optional) entities I am interested in?

You don't need two outer joins. You could simply use this HQL and Hibernate will add the right children to the right parent:

List<Parent> parentList = session
        .createQuery("from Parent p left join fetch p.children c" +
                     " where p.status = 'COMPLETE' " + 
                     " and (c.key = 'FIRST_KEY' or c.key = 'SECOND_KEY')")
        .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
        .list();

for(Parent parent:parentList) {
    System.out.println(parent);;
}

Hope that solves your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM