mapping article and category entity to my article_category table
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.
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.
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
精彩评论