Searching...
Friday, 16 August 2013

Hibernate One to Many Mapping Example Using Annotations

09:03

One to Many Relationships

According to the Relational Database One to Many is one record in a table is related to many records in other table. In this example we are going to implement this using Hibernate Annotations.

Let us consider Student and Books relation ship , one Student can have many number of books, see how can we map these relations via annotations. 

Software Used

Java 1.7

Hibernate 3

MySql 5

Eclipse

1. Create a Maven Project with below dependencies

<dependencies>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib-nodep</artifactId>
            <version>2.1_3</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.17</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-annotations</artifactId>
            <version>3.5.6-Final</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.5</version>
        </dependency>
        <dependency>
            <groupId>javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.9.0.GA</version>
        </dependency>
    </dependencies>

2. Create Book entity (Book.java)

package com.vinod.hibernate.onetomany;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "Book")
public class Book{
    @Id
    @Column(name = "bookid")
    private int bookId;
 
    @Column(name = "bookname", length=10)
    private String bookName;
 
    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;
    }
}

3. Create Student entity (Student.java)

package com.vinod.hibernate.onetomany;
 
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "Student")
public class Student{
    @Id
    @Column(name = "studentid")
    private int studentId;
   
    @Column(name = "studentname", length=10)
    private String studentName;
   
    @OneToMany(fetch=FetchType.LAZY, targetEntity=Book.class, cascade=CascadeType.ALL)
    @JoinColumn(name = "book_studentid", referencedColumnName="studentid")
   
    private Set book;
    public int getstudentId() {
        return studentId;
    }
    public void setstudentId(int studentId) {
        this.studentId = studentId;
    }
    public String getstudentName() {
        return studentName;
    }
    public void setstudentName(String studentName) {
        this.studentName = studentName;
    }
    public Set getbook() {
        return book;
    }
    public void setbook(Set book) {
        this.book = book;
    }  
}

 

Note:
The @OneToMany annotation is used to create the one-to-many relationship between the Student and Book
In the above Student class we used Collection of Books (Used Set implementation)

4. Create Hibernate Configuration File (hibernate.cfg.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="connection.driver_class">
            com.mysql.jdbc.Driver
        </property>
        <property name="connection.url">
            jdbc:mysql://localhost:3306/hibernateschema
        </property>
        <property name="connection.username">
            root
        </property>
        <property name="connection.password">
            root
        </property>
        <property name="connection.pool_size">5</property>
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <mapping class="com.vinod.hibernate.onetomany.Student"></mapping>
        <mapping class="com.vinod.hibernate.onetomany.Book"></mapping>
    </session-factory>
</hibernate-configuration>
 

4. Create a Main class and Run it. (StudentMain.java)

package com.vinod.hibernate.onetomany;
import java.util.HashSet;
import java.util.Set;
 
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
 
public class StudentMain {
    private static SessionFactory sessionFactory;
    public static void main(String[] args) {
        try {
            sessionFactory = new AnnotationConfiguration().configure("hibernate_one_to_many.cfg.xml")
                    .buildSessionFactory();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        Session session = sessionFactory.openSession();
        Student student = new Student();
        student.setstudentId(2);
        student.setstudentName("Raman");
        Book book1 = new Book();
        book1.setbookId(14);
        book1.setbookName("Science");
        Book book2 = new Book();
        book2.setbookId(15);
        book2.setbookName("Maths");
        Set books = new HashSet();
        books.add(book1);
        books.add(book2);
        student.setbook(books);
        Transaction tx = session.beginTransaction();
        session.save(student);
        tx.commit();
        session.close();
        System.out.println("Student Record Saved");
        sessionFactory.close();
    }
}

5. Output

Hibernate: select book_.bookid, book_.bookname as bookname1_ from Book book_ where book_.bookid=?

Hibernate: select book_.bookid, book_.bookname as bookname1_ from Book book_ where book_.bookid=?
Hibernate: insert into Student (studentname, studentid) values (?, ?)
Hibernate: insert into Book (bookname, bookid) values (?, ?)
Hibernate: insert into Book (bookname, bookid) values (?, ?)
Hibernate: update Book set book_studentid=? where bookid=?
Hibernate: update Book set book_studentid=? where bookid=?
Student Record Saved

image

 

image 

6. Download Example

Hibernate one to many example

0 comments: