Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate HQL Query to get parent + children based on childID

I have an object with several @onetomany relationships, and I need to query for properties in the parent, as well as properties of the children. I can't seem to get it done.

For example, I need a query that lets me see the Parent objects where where the parent's name is "John" and the child's favorite color is blue. Hope that makes sense. The reason for the complication seems to be that children are in a list, not in a @onetoone relationship.

PARENT:
@Entity
@Table(name="Parent")
public class Parent {
    @Id
    @Column(name="ID")
    @GeneratedValue(strategy=GenerationType.AUTO, generator="parent_gen")
    @SequenceGenerator(name="parent_gen", sequenceName="PARENT_SEQUENCE")
    private int parentID;

    @Column(name="name")
    private String name;

    @OneToMany(cascade=CascadeType.ALL)
    @OrderBy("name ASC")
    @JoinTable(name = "parent_to_child")
    private List<Child> childList;
    // and so forth

Child 
@Entity
@Table(name="Child")
public class Child{
    @Id
    @Column(name="ID")
    @GeneratedValue(strategy=GenerationType.AUTO, generator="child_gen")
    @SequenceGenerator(name="child_gen", sequenceName="CHILD_SEQUENCE")
    private int childID;

    @Column(name="favoriteColor")
    private String favoriteColor;

    // and so forth
like image 261
Jorge Avatar asked Jun 13 '12 22:06

Jorge


2 Answers

select p from Parent p join p.childList c
    where p.name = 'John' and c.favoriteColor = 'blue'

This will return a List<Parent>.

You can look all this in the hql reference

like image 143
Pablo Avatar answered Nov 18 '22 18:11

Pablo


Try something as follows:

from Parent as parent
    left join parent.childList as children
        with children.favoriteColor = 'blue'
where parent.name = 'John'
like image 1
Bhesh Gurung Avatar answered Nov 18 '22 20:11

Bhesh Gurung