tags:

views:

21

answers:

1

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, you have several tags. The same as for tag.

What I would like to do is to get all questions (and their corresponding tags) if the question contain a tag says "hibernate".

I can at most do it with a SQLQuery in the many-to-many table and return a list of the question ID. Then use a criteria with a restrictions.in and grab all questions. But it's too clumsy and I bet there is a better way of doing it, is there?

+3  A: 

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

lomaxx
I should have asked much earlier! Couldn't believe it's so straight forward.
Yau Leung
Thanks @lomaxx , I have the same question but with a little different requirement : What if I want to compare the "qt" with a Tag object ? (not qt.name with tag.getName())
smallufo
@smallufo : what do you mean? are you saying you have a tag and you want to compare the qt.Tags collection to that tag? In that case you need to do Restrictions.eq("qt.Tags.Id", tag.Id)
lomaxx
@Iomaxx , I mean I want to do tag's equality test : equals() , not just one property (id or name).
smallufo
@smallufo : that's not something hibernate can handle for you. It's something java will have to deal with
lomaxx