“Many-to-many” example
This is a many-to-many relationship table design, a STOCK table has more than one CATEGORY, and CATEGORY can belong to more than one STOCK, the relationship is linked with a third table called STOCK_CATEGORY.

Hibernate implementation
In Hibernate, this “many-to-many” relationship can implemented in two ways :
- Hibernate XML Mapping file
- Hibernate Annotation
1. Hibernate XML mapping file
In XML mapping way, you need three Java classes to hold the table data,
- Stock.java -> STOCK table
- Category.java -> CATEGORY table
- StockCategory.java -> STOCK_CATEGORY table
and three XML mapping files to describe the table relationship.
- Stock.hbm.xml -> STOCK table
- Category.hbm.xml -> CATEGORY table
- StockCategory.hbm.xml -> STOCK_CATEGORY table
Stock.java
public class Stock implements java.io.Serializable { private Set<StockCategory> stockCategories = new HashSet<StockCategory>(0); ... public Set<StockCategory> getStockCategories() { return this.stockCategories; } public void setStockCategories(Set<StockCategory> stockCategories) { this.stockCategories = stockCategories; }
Category.java
public class Category implements java.io.Serializable { private Set<StockCategory> stockCategories = new HashSet<StockCategory>(0); ... public Set<StockCategory> getStockCategories() { return this.stockCategories; } public void setStockCategories(Set<StockCategory> stockCategories) { this.stockCategories = stockCategories; }
StockCategory.java
public class StockCategory implements java.io.Serializable { private Integer stockCategoryId; private Stock stock; private Category category; ...
Stock.hbm.xml
... <class name="com.mkyong.common.Stock" table="stock" ...> <id name="stockId" type="java.lang.Integer"> <column name="STOCK_ID" /> <generator class="identity" /> </id> ... <set name="stockCategories" inverse="true" lazy="true" table="stock_category" ...> <key> <column name="STOCK_ID" not-null="true" /> </key> <one-to-many class="com.mkyong.common.StockCategory" /> </set> ...
Set inverse=”true” in set variable, Stock does not want to maintain the relationship.
Category.hbm.xml
... <class name="com.mkyong.common.Category" table="category" ...> <id name="categoryId" type="java.lang.Integer"> <column name="CATEGORY_ID" /> <generator class="identity" /> </id> ... <set name="stockCategories" inverse="true" lazy="true" table="stock_category" ...> <key> <column name="CATEGORY_ID" not-null="true" /> </key> <one-to-many class="com.mkyong.common.StockCategory" /> </set> ...
Set inverse=”true” in set variable, Category does not want to maintain the relationship also.
StockCategory.hbm.xml
... <class name="com.mkyong.common.StockCategory" table="stock_category" ...> <id name="stockCategoryId" type="java.lang.Integer"> <column name="STOCK_CATEGORY_ID" /> <generator class="identity" /> </id> <many-to-one name="stock" class="com.mkyong.common.Stock" ...> <column name="STOCK_ID" not-null="true" /> </many-to-one> <many-to-one name="category" class="com.mkyong.common.Category" ...> <column name="CATEGORY_ID" not-null="true" /> </many-to-one> </class> ...
StockCategory maintain the relationship between Stock and Category, see inverse=”true” explanation.
2. Hibernate annotation
In annotation way, three classes are required, all the relationships are declared inside the Java classes.
- Stock.java -> STOCK table
- category.java -> CATEGORY table
- StockCategory.java -> STOCK_CATEGORY table
Stock.java
... @Entity @Table(name = "stock", catalog = "mkyong", uniqueConstraints = { @UniqueConstraint(columnNames = "STOCK_NAME"), @UniqueConstraint(columnNames = "STOCK_CODE") }) public class Stock implements java.io.Serializable { private Set<StockCategory> stockCategories = new HashSet<StockCategory>(0); ... @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "STOCK_ID", unique = true, nullable = false) public Integer getStockId() { return this.stockId; } ... @OneToMany(fetch = FetchType.LAZY, mappedBy = "stock") public Set<StockCategory> getStockCategories() { return this.stockCategories; } public void setStockCategories(Set<StockCategory> stockCategories) { this.stockCategories = stockCategories; } ...
Category.java
... @Entity @Table(name = "category", catalog = "mkyong") public class Category implements java.io.Serializable { private Set<StockCategory> stockCategories = new HashSet<StockCategory>(0); ... @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "CATEGORY_ID", unique = true, nullable = false) public Integer getCategoryId() { return this.categoryId; } ... @OneToMany(fetch = FetchType.LAZY, mappedBy = "category") public Set<StockCategory> getStockCategories() { return this.stockCategories; } public void setStockCategories(Set<StockCategory> stockCategories) { this.stockCategories = stockCategories; } ...
StockCategory.java
@Entity @Table(name = "stock_category", catalog = "mkyong", uniqueConstraints = @UniqueConstraint(columnNames = { "STOCK_ID", "CATEGORY_ID" })) public class StockCategory implements java.io.Serializable { private Integer stockCategoryId; private Stock stock; private Category category; ... @Id @GeneratedValue(strategy = IDENTITY) @Column(name = "STOCK_CATEGORY_ID", unique = true, nullable = false) public Integer getStockCategoryId() { return this.stockCategoryId; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "STOCK_ID", nullable = false) public Stock getStock() { return this.stock; } @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "CATEGORY_ID", nullable = false) public Category getCategory() { return this.category; } ...
The code is self-explanatory, all the @annotation are the XML mapping tag substitution.
Test It
Run the example, both annotation and XML mapping file will generate the same output. Hibernate inserts a row into the STOCK table, a row into the CATEGORY table, and both relationship in STOCK_CATEGORY table.
Stock stock = new Stock(); Category category = new Category(); ... session.save(stock); session.save(category); ... StockCategory stockCategory = new StockCategory(stock, category); session.save(stockCategory);
Output
Hibernate:
insert into mkyong.stock
(STOCK_CODE, STOCK_NAME)
values (?, ?)
Hibernate:
insert into mkyong.category
(`DESC`, NAME)
values (?, ?)
Hibernate:
insert into mkyong.stock_category
(CATEGORY_ID, STOCK_ID)
values (?, ?)
Popularity: 2% [?]
No related posts.
Related posts brought to you by Yet Another Related Posts Plugin.
RSS Feed
Twitter

февруари 8th, 2010
admin
Posted in 

I find your site to be very useful, lots of good information keep it up.
Hi I found your site by mistake when i was searching yahoo for this
Substantially, the post is actually the freshest topic on this related issue. I harmonize with your conclusions and will thirstily look forward to your incoming updates. Saying thanks will not just be adequate, for the great clarity in your writing. I will instantly grab your rss feed to stay privy of any updates.
wow, awesome post, I was wondering
i probably would not have figured this had been outstanding one or two years back then again its amusing precisely how time switches the means by which you understand many concepts, thank you regarding the posting it is actually nice to go through anything clever now and then in lieu of the customary garbage mascarading as blogs on the web, cheers
Good blogpost, I bookmarked your site so I can visit again in the near future, Thanks
Affiliate marketing is one of the best ways to begin your business. It is very cost effective to begin and has great potential for earnings. Affiliate marketing is a great way to start off your business by earning some capital to begin your enterprise. Once you are starting to earn you can develop your business knowing you have a good source of income. http://www.articlecanyon.com/internet/how-to-start-an-online-business-as-an-affiliate.html
Do you know that your site looks a little bit weird in Mozilla on my laptop with Mac .
Hey, Found your blog on Yahoo and I will definatley be recommending and coming back to the site! =), i would like to add that is very hard to be lonely in this world.
Very beautiful babe, slim, petite, sexy, very funny and serious. Looking for new friends. I like men who are open-minded, know how to cook really well, cultured and well-traveled. They are established in their career. Dress well. Active and good looking.Looking for a good looking boyfriend.
Keep posting stuff like this i really like it
I like it very much! Just incredible! Your composition manner is pleasing and the way you dealt the topic with grace is notable. I am intrigued, I make bold you are an expert on this topic. I am signing up for your incoming updates from now on.
Apple now has Rhapsody as an app, which is a great start, but it is currently hampered by the inability to store locally on your iPod, and has a dismal 64kbps bit rate. If this changes, then it will somewhat negate this advantage for the Zune, but the 10 songs per month will still be a big plus in Zune Pass’ favor.
Erin Andrews Hidden Peephole videos. New Release…
We have the right to watch Erin Andrews peephole videos. New hidden videos have been released from court, showing all you want to see from Erin. Click the above link and download and share the videos before her lawyers delete them….
…
Ok. I think you are right. Could you please take a look at the best Imperial foosball table guide!…
…
This can be definitely fantastic news. Thank you for discussing it with us!…