Hibernate HQL to Criteria

I'm trying to translate a simple HQL to Criteria API, can anyone help me? This is my HQL:

SELECT ch FROM Parent p JOIN p.childeren ch WHERE p.id = :id

As a result I get children. Important thing is there there is no relation from Child to Parent. There is only relation in Parent to children like this:

@OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.ALL })
@JoinColumn(name="parent_id")
private List children;

How can I get the same results using criteria-api?


Only fetching an associated entity is a huge pain using the Criteria API. You would need sub-queries:

    DetachedCriteria subCriteria = DetachedCriteria.forClass(Parent.class);
    subCriteria.createCriteria("children", "c");
    subCriteria.setProjection(Projections.property("c.id"));
    subCriteria.add(Restrictions.eq("id", 1));
    // Assuming Children is the name of the class
    Criteria criteria = sess.createCriteria(Children.class);
    criteria.add(Subqueries.propertyIn("id", subCriteria));
    criteria.list();

A possible solution for this problem is to use sqlRestriction , as in example below, but this is not nice because it requires to use database column name.

Criteria crit = sessionFactory.getCurrentSession().createCriteria(Child.class); crit.add(Restrictions.sqlRestriction("{alias}.parent_id = ?", parentId, LongType.INSTANCE));

Does someone have a better solution?


你不需要查询这个,因为你可以这样做:

Set<Child> children = session.get(Parent.class, id).getChildren();
children.size(); // trigger lazy initialization
链接地址: http://www.djcxy.com/p/36994.html

上一篇: Hibernate查询与标准的关联:'和'关于孩子?

下一篇: Hibernate HQL to Criteria