Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Hibernate Hibernaterelationships Hibernate Many-to-many Relationships

Related Tutorials


 
 

Share on Google+Share on Google+

Hibernate Many-to-many Relationships

Advertisement
In this example we have used xml metadata.

Hibernate Many-to-many Relationships

     

Hibernate Many-to-many Relationships - Many to many example in Hibernate. In this example we have used xml metadata.

Now we will learn many-to-many relationships. Let's try many-to-many example. The many-to-many tag is used to define the relationships. The extra table is required in the database to persist the relationship, we will use author_book table to persist the relationship between Author and Book entities. Let's get started with Many-to-many relationship.

Many-to-Many Relationships

In case of many-to-many relationships, each row in table A linked to multiple rows in table B and vice versa. Here we will implement many-to-many relationship between two entries Author and Book. A book might be authored by multiple author and one author might author many books.

We are using two tables author and book and java entities Author and Book maps respectively. Here is the ER diagram

Java Persistence Objects:

The code for Author.java is given below:

package roseindia;

import java.util.Set;


public class Author {
  
  private int id;
  private String authorName;
  private Set books;
  
  /**
 @return the id
 */
  public int getId() {
  return id;
  }
  /**
 @param id the id to set
 */
  public void setId(int id) {
  this.id = id;
  }
  /**
 @return the authorName
 */
  public String getAuthorName() {
  return authorName;
  }
  /**
 @param authorName the authorName to set
 */
  public void setAuthorName(String authorName) {
  this.authorName = authorName;
  }

  public Set getBooks() {
  return books;
  }
  public void setBooks(Set books) {
  this.books = books;
  }

}

The code for Book.java is given below:

package roseindia;

import java.util.Set;


public class Book {
  
  private int id;
  private String bookName;
  private Set authors;
  
  /**
 @return the id
 */
  public int getId() {
  return id;
  }
  /**
 @param id the id to set
 */
  public void setId(int id) {
  this.id = id;
  }
  /**
 @return the bookName
 */
  public String getBookName() {
  return bookName;
  }
  /**
 @param bookName the bookName to set
 */
  public void setBookName(String bookName) {
  this.bookName = bookName;
  }
  
  /**
 @return the books
 */

  public Set getAuthors() {
  return authors;
  }
  public void setAuthors(Set authors) {
  this.authors = authors;
  }
  

}

Mapping xml file (author.hbm.xml:

This file contains the mapping for both the entities Author and Book which maps with the tables author and group respectively.

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="roseindia.Author" table="author">

<id name="id" type="int" column="id" unsaved-value="0">

<generator class="increment" />

</id>

<property name="authorName" type="java.lang.String" column="authorName"

not-null="true" length="50" />

<set name="books" table="author_book" cascade="all">

<key column="authorId" />

<many-to-many column="bookId" class="roseindia.Book" />

</set>

</class>

<class name="roseindia.Book" table="book">

<id name="id" type="int" column="id" unsaved-value="0">

<generator class="native" />

</id>

<property name="bookName" type="java.lang.String" column="bookName"

not-null="true" length="250" />

<set name="authors" table="author_book" cascade="all">

<key column="bookId" />

<many-to-many column="authorId" class="roseindia.Author" />

</set>

</class>

</hibernate-mapping>

 

 

The following mapping tag defines the many-to-many mapping between Author and Book entities from the Author entity.

<set name="books" table="author_book" cascade="all">

<key column="authorId" />

<many-to-many column="bookId" class="roseindia.Book" />

</set>

Here  table="author_book"  is the name of table which is used to define the relationships between the two entities and authorId is the foreign key of table author. Similarly bookId is the foreign key of book table. Following code defines the many-to-many relationships from the Book entity.

<set name="authors" table="author_book" cascade="all">

<key column="bookId" />

<many-to-many column="authorId" class="roseindia.Author" />

</set>

 

 

In Group.java we have stories variable of the list type, so we have used the <list../> tag here. The <one-to-many ../> specifies the one to many relationships to Story entity.

Running the Program:

To run and test the program you have to execute the ManyToManyRelation.java. Here is the full code of ManyToManyRelation.java file:

package roseindia;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;


public class ManyToManyRelation {


  public static void main(String[] args) {
  
  SessionFactory sessFact = null;
  Session session = null;
  try {
  sessFact=new Configuration().configure().buildSessionFactory();
  session=sessFact.openSession();
  
  Transaction tr = session.beginTransaction();
  
  
  //One author and may books
  Author author = new Author();  
  author.setAuthorName("John");
  
  Author author2 = new Author();  
  author2.setAuthorName("Deepak");
  
  
  Set bookSet = new HashSet();
  //Solaris
  Book bookSolaris = new Book();
  bookSolaris.setBookName("Solaris in a week");
  bookSet.add(bookSolaris);
  
  //Linux
  Book bookLinux = new Book();
  bookLinux.setBookName("Linux in a week");
  bookSet.add(bookLinux);  
  
  //Oracle
  Book bookOracle = new Book();
  bookOracle.setBookName("Oracle in a week");
  bookSet.add(bookOracle);  
  
  //Add book set to the author object
  author.setBooks(bookSet);
  
  session.save(author);
  
  
  
  /*
  Book book = new Book();

  book.setBookName("Phoenix");
  
  Author author = new Author();
  Author author1 = new Author();
  Author author2 = new Author();
  Author author3 = new Author();
  author.setAuthorName("Clifford Geertz");
  author1.setAuthorName("JP Morgenthal");
  author2.setAuthorName("Yaswant Kanitkar");
  author3.setAuthorName("Phola Pandit");
  
  Set authorSet = new HashSet();
  authorSet.add(author);
  authorSet.add(author1);
  authorSet.add(author2);
  authorSet.add(author2);
  book.setAuthors(authorSet);
  
  session.save(book);
  */
  
  
  
  
  /*
  //One author and may books
  Author author = new Author();  
  author.setAuthorName("John");
  
  Author author2 = new Author();  
  author2.setAuthorName("Deepak");
  
  
  Set bookSet = new HashSet();
  //Solaris
  Book bookSolaris = new Book();
  bookSolaris.setBookName("Solaris in a week");
  bookSet.add(bookSolaris);
  
  //Linux
  Book bookLinux = new Book();
  bookLinux.setBookName("Linux in a week");
  bookSet.add(bookLinux);  
  
  //Oracle
  Book bookOracle = new Book();
  bookOracle.setBookName("Oracle in a week");
  bookSet.add(bookOracle);  
  
  //Add book set to the author object
  author.setBooks(bookSet);
  
  
  author2.setBooks(bookSet);
  
  
  session.save(author);
  session.save(author2);
  
  
  Set authors = new HashSet();
  authors.add(author);
  authors.add(author2);
  
  
  //One Book and may authors
  
  //Create Book
  Book javaBook = new Book();
  javaBook.setBookName("Java in a week");
  
  javaBook.setAuthors(authors);
  
  //Save
  session.save(javaBook);
  */
  
  //Create author set
  //Set authors = new HashSet();
  
  /*
  Author JohnAuth = new Author();
  JohnAuth.setAuthorName("John");
  authors.add(JohnAuth);

  Author deepakAuth = new Author();
  deepakAuth.setAuthorName("Deepak");
  authors.add(deepakAuth);

  Author manojAuth = new Author();
  manojAuth.setAuthorName("Manoj");
  authors.add(manojAuth);
  //Create and add authors
  
  //Add author set to book
  javaBook.setAuthors(authors);
  
  //Save
  session.save(javaBook);
 */
  
  
  /*
  //Displaying all the books for the Author 2
  Author a = (Author)session.load(Author.class, 2);
  Set book = a.getBooks();
  System.out.println(a.getAuthorName());
  
  System.out.println("total=" + book.size());  
  Iterator iter = book.iterator();
  while (iter.hasNext()) {
  
  Book b = (Book)(iter.next());
  System.out.println(b.getBookName());
  }  

  */
  tr.commit();
  System.out.println("Done");
  }
  catch(HibernateException He){
  System.out.println(He.getMessage());
  }
  finally{
  session.close();
  }

  }

}

The above code is self explanatory, we are creating the objects of Author:

Author author = new Author(); 

Then set the author name:

author.setAuthorName("John");

The create Book set and add many books:

Set bookSet = new HashSet();

//Solaris

Book bookSolaris = new Book();

bookSolaris.setBookName("Solaris in a week");

bookSet.add(bookSolaris);

//Linux

Book bookLinux = new Book();

bookLinux.setBookName("Linux in a week");

bookSet.add(bookLinux);

//Oracle

Book bookOracle = new Book();

bookOracle.setBookName("Oracle in a week");

bookSet.add(bookOracle);

 

Finally add the book set to the author object and save the author:

//Add book set to the author object

author.setBooks(bookSet);

session.save(author);

The above code will save author and the books authored by the author. You can also un-comment the comment the code in ManyToManyRelation.java and try more examples such as many Authors authoring the same book. Here is output of the program when executed in Eclipse IDE.

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).

log4j:WARN Please initialize the log4j system properly.

Hibernate: select max(id) from author

Hibernate: insert into author (authorName, id) values (?, ?)

Hibernate: insert into book (bookName) values (?)

Hibernate: insert into book (bookName) values (?)

Hibernate: insert into book (bookName) values (?)

Hibernate: insert into author_book (authorId, bookId) values (?, ?)

Hibernate: insert into author_book (authorId, bookId) values (?, ?)

Hibernate: insert into author_book (authorId, bookId) values (?, ?)

Done

 

In this section we learned about the Many-to-one relationships in Hibernate.

Download the code example

 

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: January 28, 2010

Related Tutorials

Discuss: Hibernate Many-to-many Relationships   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:3
Rohini
August 16, 2011
Hibernate

Nice Explanation
siddu
October 1, 2011
hibernate

great explanatory tutorial.........
srinu
August 4, 2012
hibernate

How to retrive data from database in one to many relationship in hibernate.plz send the code.plz.......................
DMCA.com