Searching...
Friday, 16 August 2013

Hibernate Many to Many Simple Example using Annotations

14:08
In this example we will see many to many relationships of entities. Let us consider Student and Teacher, a student can have many teacher and a teacher can have many students and this relationship is mapped with School.

Software Used

Java 1.7
Hibernate 3
MySql 5
Eclipse Juno

1. Create a Java project

Create a Java project and update Hibernate jars and Mysql driver jar in to build path. (Download Hibernate , MySql Driver)
image

2. Create Student entity (Student.java)

package com.pretech;
 
import java.util.Set;
 
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
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;
    @ManyToMany(targetEntity=Teacher.class,cascade=CascadeType.ALL)
    @JoinTable(name="school",joinColumns=@JoinColumn(name="student_id",referencedColumnName="studentid"),inverseJoinColumns=@JoinColumn(name="teacher_id",referencedColumnName="teacherid"))
    private Set teachers;
 
    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 getTeachers() {
        return teachers;
    }
    public void setTeachers(Set teachers) {
        this.teachers = teachers;
    }
}

3. Create a Teacher entity (Teacher.java)

package com.pretech;
 
import java.util.Set;
 
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
 
@Entity
@Table(name="teacher")
public class Teacher
{
    @Id
    @Column(name="teacherid")
    private int teacherid;
    @Column(name="teachername",length=10)
    private String teachername;
    @ManyToMany(targetEntity=Student.class,mappedBy="teachers")
    private Set  student;
    public int getTeacherid() {
        return teacherid;
    }
    public void setTeacherid(int teacherid) {
        this.teacherid = teacherid;
    }
    public String getTeachername() {
        return teachername;
    }
    public void setTeachername(String teachername) {
        this.teachername = teachername;
    }
    public Set getStudent() {
        return student;
    }
    public void setStudent(Set student) {
        this.student = student;
    }
}

4. Create Hibernate config 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 name="studentFactory">
            <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.pretech.Teacher"></mapping>
<mapping class="com.pretech.Student"></mapping>
</session-factory>
</hibernate-configuration>

5. Create a Main program and run it

package com.pretech;
 
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 ManytoManyMain {
    private static SessionFactory sessionFactory;
 
    public static void main(String args[])
    {
        try {
            sessionFactory = new Configuration().configure("hibernate.cfg.xml")
                    .buildSessionFactory();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        Session session = sessionFactory.openSession();
 
        Student st1 = new Student();
        st1.setStudentId(10);
        st1.setStudentname("Student 1");
 
        Student st2=new Student();
        st2.setStudentId(11);
        st2.setStudentname("Student 2");
 
        Teacher t1=new Teacher();
        Teacher t2 = new Teacher();
 
        t1.setTeacherid(21);
        t1.setTeachername("Teacher 1");
 
        t2.setTeacherid(22);
        t2.setTeachername("Teacher 2");
 
        Set  s =new HashSet();
        s.add(t1);
        s.add(t2);
 
        st1.setTeachers(s);
        st2.setTeachers(s);
 
        Transaction tx = session.beginTransaction();
        session.save(st1);
        session.save(st2);
        tx.commit();
        System.out.println("Student and Teacher records saved");
        session.close();
    }
 
}

6. Output


Hibernate: select teacher_.teacherid, teacher_.teachername as teachern2_0_ from teacher teacher_ where teacher_.teacherid=?
Hibernate: select teacher_.teacherid, teacher_.teachername as teachern2_0_ from teacher teacher_ where teacher_.teacherid=?
Hibernate: insert into student (studentname, studentid) values (?, ?)
Hibernate: insert into teacher (teachername, teacherid) values (?, ?)
Hibernate: insert into teacher (teachername, teacherid) values (?, ?)
Hibernate: insert into student (studentname, studentid) values (?, ?)
Hibernate: insert into school (student_id, teacher_id) values (?, ?)
Hibernate: insert into school (student_id, teacher_id) values (?, ?)
Hibernate: insert into school (student_id, teacher_id) values (?, ?)
Hibernate: insert into school (student_id, teacher_id) values (?, ?)
Student and Teacher records saved
image image
                                                     image 

7. Download this example

Hibernate Many to Many Example

0 comments: