Need help with some Hibernate relational mappings

These are the tables I want to map using Hibernate:

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

      

I've looked at the documentation for Hibernate, but I really can't seem to pick which type of mapping is most appropriate for my tables.

Any help would be greatly appreciated! :)

+2


source to share


2 answers


For custom article relationships, you can use either Set or List displayed as a bag; The list tends to be more convenient to look at on the java side, especially if the article has an attribute by which you can sort the collection (like creation date). Display example:

<!-- 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 are bundled as bidirectional and the article is responsible for maintaining the relationship (this avoids unnecessary updates during collection changes). Details here . Replace <set>

with <bag>

if you prefer to use List instead of Set; you can add "order-by" attribute to sort the list in the database.

For a category, you could theoretically do the same, however if your category's hierarchy is deep and you need to retrieve certain levels / subtrees quite often, consider using a nested collection model .

+1


source


  • Usage has OneToMany mapping for articles (one user creates many articles);
  • The article has a ManyToOne mapping for the user;
  • The category has a OneToMany display for yourself (children);
  • The category has a ManyToOne mapping for itself (parent).


In both cases, communication does not have to be bidirectional, but most of the time it is.

+1


source







All Articles