0
votes

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?

3
no relation from Child to Parent? Show us your mappings, please.Don Roby
Original problem is not about children and parents. I have changed it to make my question more clear.m-szalik

3 Answers

1
votes

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();
0
votes

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?

0
votes

You don't need a query for this, because you can do:

Set<Child> children = session.get(Parent.class, id).getChildren();
children.size(); // trigger lazy initialization