Querying Hibernate Parent/Child with Subquery Criteria

EDIT: relevant: https://forum.hibernate.org/viewtopic.php?f=1&t=946236&start=0 but still no solution there.

I have a parent/child relationship. The parent maps a set of string tags. The simplified DDL:

CREATE TABLE PARENT ( 
  ID        NUMBER(38,0) NOT NULL,
   {other columns here}
  CONSTRAINT PK_PARENT PRIMARY KEY ("ID") 
)

CREATE TABLE TAGS ( 
  PARENT_ID NUMBER(38,0) NOT NULL,
  NAME      VARCHAR2(100) NOT NULL,
  CONSTRAINT CHILD_PARENT_FK FOREIGN KEY ("PARENT_ID") REFERENCES PARENT("ID") 
)

The child table has a foreign key to the parent table, and a varchar called name.

The parent class maps the child as a Set

public class Parent {
  public Set<String> getTags() { return tags; }
  public void setTags(Set<String> tags) { this.tags = tags; }
}

The mapping

<class name="com.example.Parent" table="parent">
  <set name="tags" table="tags" order-by="name asc">
    <key column="parent_id"/>
    <element type="string" column="name"/>
  </set>
</class>

This sqlRestriction query does exactly what I want to do:

return session.createCriteria(Parent.class)
   .add(Restrictions.sqlRestriction(
     "EXISTS (SELECT 1 FROM tags t WHERE t.parent_id = {alias}.id "+
     "AND t.name in ('tag1', 'tag2', 'tag3') )" ) );

This finds me all Parent objects that have tags that match any of 'tag1', 'tag2', 'tag3'.

I need to translate this into a Criteria based query b/c we use Criteria for all the other properties, and I need to find a way to do the same for this: essentially convert this into a Criterion or a DetachedCriteria that I can use as part of a larger expression .

The problem I am having is that most examples that are similar have a Parent and Child Entity class, where the child class is a bona-fide entity. You can thus create Criteria like:

session.createCriteria(Parent.class, "p").createCriteria("tags").etc...

If I try to do this, Hibernate throws a mapping exception and complains that "tags" is not an association. The mapping is correct, however. If I query for parent types, it returns me the child tags just fine in the Set -- I just can't figure out how to query it with some combination of Criteria, Subqueries, Restrictions, DetachedCriteria, etc.

I would love to hear any suggestions.

链接地址: http://www.djcxy.com/p/6316.html

上一篇: 如何在休眠条件中添加“on”子句?

下一篇: 使用子查询条件查询Hibernate父/子