views:

88

answers:

2

These are the tables I want to map using Hibernate:

user (PK UserId)
article (PK ArticleId, FK CreatorUserId)
category (PK CategoryId, FK ParentCategoryId)

I have been looking at the documentation for Hibernate, but I really cannot choose what type of mapping is the most suitable for my tables.

Any help would be greatly appreciated! :)

+1  A: 
  • Use has a OneToMany mapping to Articles (one user creates many articles);
  • Article has a ManyToOne mapping to User;
  • Category has a OneToMany mapping to itself (children);
  • Category has a ManyToOne mapping to itself (parent).

In both cases, the relationship doesn't need to be bidirectional but most of the time it is.

cletus
Thank you for your comment. Should I use the "set"-tag to specify the one-to-many relation for User > Articles? If so, what should be the value of the key column attribute in the set mapping for the user?
Mickel
I'm more familiar with the JPA annotation style mapping than the XML Hibernate-specific mapping.
cletus
That looks alot simpler. Does the JPA annotation support relational mappings as well?
Mickel
+1  A: 

For user-articles relationship you can use either Set or List mapped as bag; List tends to be a bit more convenient to deal with on java side especially if article has an attribute by which you may want to sort the collection (e.g. creation date). Sample mapping is:

<!-- within User mapping -->
<set name="articles" table="article" inverse="true">
  <key column="CreatorUserId"/>
  <one-to-many class="Article"/>
</set>

<!-- within Article mapping -->
<many-to-one name="creatorUser" class="User" column="CreatorUserId" not-null="true"/>

The above maps association as bidirectional with Article being responsible for maintaining the relationship (this avoids an unnecessary update during collection changes). Details are here. Replace <set> with <bag> if you'd rather use List in place of Set; you can then add "order-by" attribute to have your list sorted in the database.

For Category you could in theory do the same, however if your category hierarchy is deep and you need to retrieve specific levels / sub-trees rather often, consider using nested set model instead.

ChssPly76