These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: many-to-many issue
PostPosted: Thu Nov 27, 2008 5:19 pm 
Newbie

Joined: Thu Nov 27, 2008 4:48 pm
Posts: 2
Hello. I've got 2 pojos and 3 tables:

Entity: Article
Code:
mysql> select id, title from articles;
+----+----------+
| id | title    |
+----+----------+
|  1 | foo      |
|  2 | bar      |
|  3 | test     |
|  4 | example  |
|  5 | demo     |
+----+----------+


Entity: Category
Code:
mysql> select id, title from categories;
+----+----------+
| id | title    |
+----+----------+
|  1 | cat1     |
|  2 | cat2     |
|  3 | cat3     |
+----+----------+


Code:
<set name="categories" table="article_categories">
<key column="article_id" />
<many-to-many column="category_id" class="com.Category" />
</set>

many-to-many table generated from the above hibernate mapping:
Code:
mysql> select * from article_categories;
+------------+-------------+
| article_id | category_id |
+------------+-------------+
|          1 |           1 |
|          1 |           2 |
|          1 |           3 |
|          2 |           1 |
|          2 |           3 |
|          3 |           3 |
|          5 |           3 |
+------------+-------------+


I'd like to be able to do the following (expressed in sql) in hql:
Code:
mysql> select id from articles, article_categories where
articles.id=article_categories.article_id and category_id in (1,2);
+----+
| id |
+----+
|  1 |
|  2 |
+----+


Is it possible?

I did it with SQLQuery but not HQL and I need it in HQL in order to be able to use the query cache for it.

In HQL I managed to do it but it joins all 3 tables and I don't want that:
Code:
select a.id from Article a join a.categories as c where c.id in (1, 2)


Top
 Profile  
 
 Post subject:
PostPosted: Fri Nov 28, 2008 2:51 am 
Newbie

Joined: Thu Nov 27, 2008 4:48 pm
Posts: 2
OK I've found a solution:
Code:
session.createCriteria(Article.class).
    setProjection(Projections.projectionList().add(Projections.property("id"))).
    add(Restrictions.sqlRestriction(
        "{alias}.id in " +
        "(select article_id from article_categories where category_id in (1, 2))")).
    list();


thanks


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.