Jha
Jha

Reputation: 127

Hibernate: One to many relation where clause

I have two tables

Table 1 (Parent)
    parent_Id
    Name

Table2 (Child)
    child_Id
    Name
    Parent_id
    version

Corresponding classes are

Class Parent
{
    Int parentId;
    String name;
    Set<Child> childList;

    @Id
    @Column(name="PARENT_ID")
    public int getParentId()
    {
       return parentId;
    }
   @Column(Name="NAME"
   public String getName()
   {
     return name;
   }
   @OneToMany(mappedBy="parent",fetch=FetchType.EAGER)
   @OrderBy("pareantId")

   public Set<Child> getChildList()
   {
      return childList;
   }

}

   Class Child {
      Int childId;
    String name;
    Parent parent;
    int age;

    @Id
    @Column(name="CHILD_ID")
    public int getId()
    {
       return childId;
    }
   @Column(Name="NAME"
   public String getName()
   {
     return name;
   }
   @ManyToOne
   @JoinColumn(name = "PARENT_ID", nullable = false) 
   public A getParent()
   {
      return parent;
   }

   public getAge()
   {
     return age;
   }

} This is my DAO class which is working fine if I just use in query (from parent where parentId=1).

@Transactional
    public Parent getParentBy(int id) 
    {
        Parent parent = null;
        Session session = this.sessionFactory.getCurrentSession();
        try{
        parent =(Parent) session.createQuery("from Parent where parentId=? ).setParameter(0,id).uniqueResult();

        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return parent;
    }

When I am running this I am getting all the childs under that parent in the set.

Now, what I need to do if I want to add the where clause for age in the same above query? Is that possible? Can we write like this

from Parent as a where a.parentId=? and a.childList.age> 10

Logically this doen't look proper. Any help will be appreciated.

Thanks

Upvotes: 0

Views: 2631

Answers (1)

Rafa
Rafa

Reputation: 2027

Take a look at the documentation. You may need join Parent and childList in your HQL. Try something like:

from Parent as a 
left join a.childList as child with child.age> 10
where a.parentId=?

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-joins

Upvotes: 1

Related Questions