Hibernate many-to-many: Criteria for looking up all class A which contains class B

后端 未结 1 458
执念已碎
执念已碎 2020-12-25 09:12

I have 2 classes which have many to many relationship. I take the \'Question\' and \'Tag\' as an example to make the case more understandable.

For each question,

1条回答
  •  离开以前
    2020-12-25 09:28

    Essentially, you need to create an alias and use the alias to query the child collection like so:

    List questions = sess.createCriteria(Question.class)
        .createAlias("Tags", "t")
        .add( Restrictions.eq("t.name", "hibernate") )
        .list();
    

    I'm assuming you don't actually have a class that represents the "bridge" table to the tags table in this scenario, otherwise you'd need to create 2 aliases eg:

    List questions = sess.createCriteria(Question.class)
            .createAlias("QuestionTag", "qt")            
            .createAlias("qt.Tags", "t")
            .add( Restrictions.eq("t.name", "hibernate") )
            .list();
    

    You can find out more from the docs:

    http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/querycriteria.html#querycriteria-associations

    0 讨论(0)
提交回复
热议问题