views:

19

answers:

2

So I have 2 entities:

Article
Category

And I have a table that relates the articleID and categoryID:

articles_categories
-articleID
-categoryID

I am using xml for my mappings, what should I do here?

I want to be able to query for all articles in a given category.

+1  A: 

Use many to many mapping:

<class name="Article">     

<set name="Categories" table="articles_categories">
  <key column="ArticleId" />
  <many-to-many column="CategoryId" class="Category"  />
</set>


</class>

You should be able to query like a normal collection.

Torkel
how would I associate an article to a category?
mrblah
Like the mapping describes abovethe class would be like this: class Article{ ISet<Category> Categories {get;set;} }
Torkel
ok thanks. so then I should create helper methods on both classes that add to each others collections correcT?
mrblah
+1  A: 

You can approach this in two ways, depending on how you want to do it. You can set your Category class to have a Collection of Articles. Then to get all of the articles in the category you simply load the Category by id and then call getArticles().

Alternatively, you give the Article a collection of Categories that it belongs to. It all depends on your domain model. Can an article be in multiple categories?

Once you've decided that, take a look at the Hibernate documentation on mapping Collections: http://docs.jboss.org/hibernate/stable/core/reference/en/html_single/#collections

Then your query would look something like the following:

select a from Article a join a.categories c where c.categoryID = :yourCategoryId
BryanD