Hibernate:一对多关系where子句

时间:2013-08-14 20:46:42

标签: hibernate one-to-many fetch where-clause

我有两张桌子

Table 1 (Parent)
    parent_Id
    Name

Table2 (Child)
    child_Id
    Name
    Parent_id
    version

对应的课程是

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;
   }

} 这是我的DAO类,如果我只是在查询中使用(从父级,其中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;
    }

当我运行这个时,我会让所有孩子都在该集合下面。

现在,如果我想在上面相同的查询中添加age的where子句,我需要做什么? 那可能吗? 我们可以这样写吗

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

逻辑上这看起来不合适。任何帮助将不胜感激。

由于

1 个答案:

答案 0 :(得分:1)

查看文档。您可能需要在HQL中加入Parent和childList。尝试类似:

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

相关问题