Hibernate - SPLessons

Hibernate Many to Many

Home > Lesson > Chapter 26
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Hibernate Many to Many

Hibernate Many to Many

shape Description

Hibernate Many to Many is a combination of one-to-many and reverse of one-to-many. When creating a POJO class, one need to use the reference variable of type collection. Hibernate Many to Many relationship means applying one-to-many relationship on both sides in two POJO classes means it is bidirectional. Collection property will be used while using Hibernate Many to Many mapping. For Example, the Book class and Author class must implement Hibernate Many to Many relationship, because it is one book as many authors(one-to-many) and one author as many books(one-to-many). In a Database, Hibernate Many to Many relationship is not applicable to two tables. .So use the third table. This third table is called as Join table. It will store foreign keys of two tables.

shape Examples

Following is an example for Hibernate Many to Many.
  • Create the project directory structure.
  • Create the persistence classes.
Book.java [java]package com.itoolsinfo; import java.util.Set; public class Book { private int bookId; private String bookName; private int price; private Set authors; public int getBookId() { return bookId; } public void setBookId(int bookId) { this.bookId = bookId; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public Set getAuthors() { return authors; } public void setAuthors(Set authors) { this.authors = authors; } } [/java] Here created the class Book with the variables bookId and bookName, set and get methods are used here to get their variables. Author.java [java]package com.itoolsinfo; import java.util.Set; public class Author { private int authorId; private String authorName; private Set book; public int getAuthorId() { return authorId; } public void setAuthorId(int authorId) { this.authorId = authorId; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public Set getBook() { return book; } public void setBook(Set book) { this.book = book; } } [/java] Like wise above program here also created the class Author with the variables authorId, authorName. Set and Get methods are performed here also.
  • Map the persistence classes in mapping file.
bookdetails.hbm.xml [xml] [xml]<!DOCTYPE hibernate-mapping PUBLIC &quot;-//Hibernate/Hibernate Mapping DTD 3.0//EN” “http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd”> <hibernate-mapping> <class name=”com.itoolsinfo.Book” table=”bookdetails”> <id name=”bookId”> <generator class=”assigned”/> </id> <property name=”bookName”/> <property name=”price”/> <set name=”authors” cascade=”all” table=”Book_Author” > <!-- table indicate the join column of two tables.  <key column=”book_fk”/> <!-- column indicate foreign key column  <many-to-many class=”com.itoolsinfo.Author” column=”author_fk”/> <!-- column indicate other class foreign key column  </set> </class> </hibernate-mapping> [/xml] The generator class subelement of id utilized to produce the unique identifier for the objects of persistence class. There are numerous generator classes characterized in the Hibernate Framework. All the generator classes actualizes the org.hibernate.id.IdentifierGenerator interface. Assigned is the default generator. author.hbm.xml [xml] <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.itoolsinfo.Author" table="authordetails"> <id name="authorId"> <generator class="assigned"/> </id> <property name="authorName"/> <set name="book" cascade="all" table="Book_Author"> <!-- table indicate the join column of two tables. --> <key column="author_fk"/> <!-- column indicate foreign key column --> <many-to-many class="com.itoolsinfo.Book" column="book_fk"/> < column indicate other class foreign key column --> </set> </class> </hibernate-mapping> [/xml] The generator classs ubelement of id utilized to produce the unique identifier for the objects of persistence class. There are numerous generator classes characterized in the Hibernate Framework. All the generator classes actualizes the org.hibernate.id.IdentifierGenerator interface.
  • Configure the mapping files in Configuration file.
hibernate.cfg.xml [xml]<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC “-//Hibernate/Hibernate Configuration DTD 3.0//EN” “http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”> “hibernate-configuration” “session-factory” <property name=”hibernate.connection.driver_class”>oracle.jdbc.driver.OracleDriver</property> <property name=”hibernate.connection.url”>jdbc:oracle:thin:@localhost:1521:xe&lt;/property” <property name=”hibernate.connection.username”<system</property> <property name=”hibernate.connection.password”>system</property> [xml]<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC “-//Hibernate/Hibernate Configuration DTD 3.0//EN” “http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd”> “hibernate-configuration” “session-factory” <property name=”hibernate.connection.driver_class”>oracle.jdbc.driver.OracleDriver</property> <property name=”hibernate.connection.url”>jdbc:oracle:thin:@localhost:1521:xe&lt;/property” <property name=”hibernate.connection.username”<system</property> <property name=”hibernate.connection.password”>system</property> <property name=”hibernate.dialect”>org.hibernate.dialect.Oracle10gDialect</property> <property name=”hbm2ddl.auto”>create</property> <property name=”show_sql”>true</property> <mapping resource=”book.hbm.xml”/> <mapping resource=”author.hbm.xml”/> </session-factory> </hibernate-configuration> [/xml]
Properties Description
hibernate.connection.driver_class The JDBC driver class.
hibernate.dialect This property makes Hibernate generate the suitable SQL for the picked database.
hibernate.connection.url The JDBC URL to the database instance.
hibernate.connection.username The database username.
hibernate.connection.password The database password.
hibernate.connection.pool_size Limits the number of connections waiting in the Hibernate database connection pool.
hibernate.connection.autocommit Allows autocommit mode to be used for the JDBC connection.
 
  • Create the SPLessons class and store the POJO class objects, to perform the database operations.
SPLessons.java [java]package com.itoolsinfo; import java.util.HashSet; import java.util.Set; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class SPLessons { public static void main(String[] args) { SessionFactory factory=new Configuration().configure("hibernate.cfg.xml").buildSessionFactory(); Session session=factory.openSession(); // create multiple Book class objects Book book1=new Book(); book1.setBookId(421); book1.setBookName(" Crime thriller "); book1.setPrice(400); Book book2=new Book(); book2.setBookId(422); book2.setBookName(" Legal Spectrum "); book2.setPrice(500); // create multiple Book class objects Author author1=new Author(); author1.setAuthorId(1); author1.setAuthorName(" Jeffrey Archer "); Author author2=new Author(); author2.setAuthorId(2); author2.setAuthorName(" Krishna lyer "); //To add the Author objects to collection type variable. Set set=new HashSet(); set.add(author1); set.add(author2); //To set the collection variable to book objects. book1.setAuthors(set); book2.setAuthors(set); Transaction transaction=session.beginTransaction(); session.save(book1); session.save(book2); transaction.commit(); } } [/java] In this class database operations will be performed as explained in the coments of the code. Output: See the output in command prompt. To see the output in Database table. [sql]select * from bookdetails;[/sql] [sql]select * from authordetails;[/sql] [sql]select * from Book_Author;[/sql]
In Many-to-Many relationship, two annotations must be used. 1. @ManyToMany(cascade = {CascadeType.ALL}) 2. @JoinTable(name="Join table name", joinColumns={@JoinColumn(name="foreign key column name")}, inverseJoinColumns={@JoinColumn(name="other class foreign key column")})
  • Create the project directory structure.
  • Create the persistence classes with Annotations.
Book.java [java]package com.itoolsinfo; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name="bookdetails") public class Book { @Id @GeneratedValue private int bookId; @Column(name="bookName") private String bookName; @Column(name="price") private int price; @ManyToMany(cascade = {CascadeType.ALL}) @JoinTable(name="Book_Author", joinColumns={@JoinColumn(name="book_fk")}, inverseJoinColumns={@JoinColumn(name="author_fk")}) private Set authors; public int getBookId() { return bookId; } public void setBookId(int bookId) { this.bookId = bookId; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public Set getAuthors() { return authors; } public void setAuthors(Set authors) { this.authors = authors; } } [/java] Annotations are used to reduce the code, here the developer has taken the same code with different annotations. The @Table comment permits you to indicate the points of interest of the table that will be utilized to hold on the element in the database. The @Table explanation gives four traits, permitting you to abrogate the name of the table, its inventory, and its composition, and uphold exceptional imperatives on sections in the table. Every element bean will have an essential key, which you comment on the class with the @Id comment. The essential key can be a solitary field or a mix of different fields relying upon your table structure. As a matter of course, the @Id comment will naturally decide the most suitable essential key era technique to be utilized however you can abrogate this by applying the @GeneratedValue explanation which takes two parameters system and generator. Author.java [java]package com.itoolsinfo; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name="authordetails") public class Author { @Id @GeneratedValue private int authorId; @Column(name="authorName") private String authorName; @ManyToMany(cascade = {CascadeType.ALL}) @JoinTable(name="Book_Author", joinColumns={@JoinColumn(name="author_fk")}, inverseJoinColumns={@JoinColumn(name="book_fk")}) private Set book; public int getAuthorId() { return authorId; } public void setAuthorId(int authorId) { this.authorId = authorId; } public String getAuthorName() { return authorName; } public void setAuthorName(String authorName) { this.authorName = authorName; } public Set getBook() { return book; } public void setBook(Set book) { this.book = book; } } [/java] Every element bean will have an essential key, which you comment on the class with the @Id comment. The essential key can be a solitary field or a mix of different fields relying upon your table structure. As a matter of course, the @Id comment will naturally decide the most suitable essential key era technique to be utilized however you can abrogate this by applying the @GeneratedValue explanation which takes two parameters system and generator.
  • Configure the persistence classes in Configuration file.
hibernate.cfg.xml [xml] <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="hibernate.connection.url"<jdbc:oracle:thin:@localhost:1521:xe</property> <property name="hibernate.connection.username">system</property> <property name="hibernate.connection.password">system</property> <property name="hibernate.dialect"<org.hibernate.dialect.Oracle10gDialect</property> <property name="hbm2ddl.auto"<create</property> <property name="show_sql">true</property> <mapping class="com.itoolsinfo.Book"> <mapping class="com.itoolsinfo.Author"> </session-factory> </hibernate-configuration> [/xml]
Properties Description
hibernate.connection.driver_class The JDBC driver class.
hibernate.dialect This property makes Hibernate generate the suitable SQL for the picked database.
hibernate.connection.url The JDBC URL to the database instance.
hibernate.connection.username The database username.
hibernate.connection.password The database password.
hibernate.connection.pool_size Limits the number of connections waiting in the Hibernate database connection pool.
hibernate.connection.autocommit Allows autocommit mode to be used for the JDBC connection.
  • Create the SPLessons class and store the POJO class objects, to perform the database operations.
SPLessons.java [java]package com.itoolsinfo; import java.util.HashSet; import java.util.Set; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.cfg.AnnotationConfiguration; public class SPLessons { public static void main(String[] args) { AnnotationConfiguration cfg=new AnnotationConfiguration(); Session session=cfg.configure("hibernate.cfg.xml").buildSessionFactory().openSession(); // create multiple Book class objects Book book1=new Book(); book1.setBookId(421); book1.setBookName(" Crime thriller "); book1.setPrice(401); Book book2=new Book(); book2.setBookId(422); book2.setBookName(" Legal Spectrum "); book2.setPrice(600); // create multiple Book class objects Author author1=new Author(); author1.setAuthorId(1); author1.setAuthorName(" Jeffrey Archer "); Author author2=new Author(); author2.setAuthorId(2); author2.setAuthorName(" Krishna lyer "); //To add the Author objects to collection type variable. Set set=new HashSet(); set.add(author1); set.add(author2); //To set the collection variable to book objects. book1.setAuthors(set); book2.setAuthors(set); Transaction transaction=session.beginTransaction(); session.save(book1); session.save(book2); transaction.commit(); } } [/java] In this class database operations will be performed. Output: See the output in command prompt. See the output in Database table using following command. [sql]select * from bookdetails;[/sql] [sql]select * from authordetails;[/sql] [sql]select * from Book_Author;[/sql]

Summary

shape Key Points

  • Hibernate Many to Many - Join table is utilized in many to many mapping to keep primary key as foreign key.
  • Join table will have only foreign keys.