close

Hibernate Many To Many Relation Mapping Example explains about how to implement A Many to Many relationship by using Hibernate

Many-to-many entity relationship , each record of an entity have multiple records in other associated entity and vice versa

On this standalone Hibernate Many To Many Mapping Example, we are using Hibernate With MySQL Database.

Required Libraries:

You need to download

  1. JDK 7
  2. Eclipse 3.7
  3. Hibernate 4.3.1
  4. Mysql 5.1.30

Following jar must be in classpath

  1. Antlr-2.7.7.jar
  2. Dom4j-1.6.1.jar
  3. hibernate-commons-annotations-4.0.4.Final.jar
  4. hibernate-core-4.3.1.Final.jar
  5. hibernate-entitymanager-4.3.1.Final.jar
  6. jandex-1.1.0.Final.jar
  7. Dom4j-1.6.1.jar
  8. jboss-logging-3.1.3.GA.jar
  9. hibernate-jpa-2.1-api-1.0.0.Final.jar
  10. jboss-transaction-api_1.2_spec-1.0.0.Final.jar
  11. Mysql-connector-java-5.1.28-bin.jar

Table Structure:

create table `employee` (
	`EMPLOYEEID` double ,
	`EMPLOYEENAME` varchar (765)
); 


create table `employee_event` (
	`EMPLOYEEID` double ,
	`EVENTID` double 
);

create table `event` (
	`EVENTID` double ,
	`EVENTNAME` varchar (765)
);

 

Create Employee & Event model classes as per the above table structure

Employee.java

package com.hibernate.manytomany;

import java.util.HashSet;
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;

@Entity
public class Employee implements java.io.Serializable {

    
private static final long serialVersionUID = 1L;

    
@Id
    @GeneratedValue
    @Column
(name = "EMPLOYEEID")
    
private long employeeId;
    
@Column(name = "EMPLOYEENAME")
    
private String employeeName;
    
@ManyToMany(cascade = CascadeType.ALL })
    
@JoinTable(name = "EMPLOYEE_EVENT", joinColumns = {@JoinColumn(name = "EMPLOYEEID") },
    inverseJoinColumns = 
@JoinColumn(name = "EVENTID") })
    
private Set<Event> events = new HashSet<Event>();

    
public Employee() {
        
super();
    
}

    
public Employee(String employeeName) {
        
super();
        
this.employeeName = employeeName;
    
}

    
public long getEmployeeId() {
        
return employeeId;
    
}

    
public void setEmployeeId(long employeeId) {
        
this.employeeId = employeeId;
    
}

    
public String getEmployeeName() {
        
return employeeName;
    
}

    
public void setEmployeeName(String employeeName) {
        
this.employeeName = employeeName;
    
}

    
public Set<Event> getEvents() {
        
return events;
    
}

    
public void setEvents(Set<Event> events) {
        
this.events = events;
    
}

}

 

 

Event.java

 

package com.hibernate.manytomany;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;

@Entity
public class Event implements java.io.Serializable {

    
private static final long serialVersionUID = 1L;
    
@Id
    @GeneratedValue
    @Column
(name = "EVENTID")
    
private long eventID;
    
@Column(name = "EVENTNAME")
    
private String eventName;
   
    
@ManyToMany(mappedBy="events")
    
private Set<Employee> employees = new HashSet<Employee>();
   
    
public Event() {
        
super();
    
}

    
public Event(String eventName) {
        
this.eventName = eventName;
    
}

    
public long getEventID() {
        
return eventID;
    
}

    
public void setEventID(long eventID) {
        
this.eventID = eventID;
    
}

    
public String getEventName() {
        
return eventName;
    
}

    
public void setEventName(String eventName) {
        
this.eventName = eventName;
    
}

    
public Set<Employee> getEmployees() {
        
return employees;
    
}

    
public void setEmployees(Set<Employee> employees) {
        
this.employees = employees;
    
}

   

}

 

 

@ManyToMany(cascade = { CascadeType.ALL }) annotation is used for linking each record of Employee table with Event table and vice versa
@JoinTable(name = "EMPLOYEE_EVENT", joinColumns = { @JoinColumn(name = "EMPLOYEEID") }, inverseJoinColumns = { @JoinColumn(name = "EVENTID") }) is used to define the join table, here it is "EMPLOYEE_EVENT", which is connecting 2 columns ie; EMPLOYEEID belongs to employee table & EVENTID belongs to event table
@Entity declares the class as an entity (i.e. a persistent POJO class)
@Table is set at the class level; it allows you to define the table, catalog, and schema names for your entity mapping. If no @Table is defined the default values are used: the unqualified class name of the entity.
@Id declares the identifier property of this entity.
@GeneratedValue annotation is used to specify the primary key generation strategy to use. If the strategy is not specified by default AUTO will be used.
@Column annotation is used to specify the details of the column to which a field or property will be mapped. If the @Column annotation is not specified by default the property name will be used as the column name.

 

 

HibernateUtil.java

 

package com.hibernate.manytomany;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {

    
private static SessionFactory    sessionFactory;
    
private static ServiceRegistry    serviceRegistry;

    
public static SessionFactory createSessionFactory() {
        
Configuration configuration = new Configuration();
        configuration.configure
("/META-INF/hibernate.cfg.xml");
        serviceRegistry = 
new StandardServiceRegistryBuilder().applySettings(configuration.getProperties())
                
.build();
        sessionFactory = configuration.buildSessionFactory
(serviceRegistry);
        
return sessionFactory;
    
}
}

 

hibernate.cfg.xml

 

hibernate.cfg.xml file must be under src/META-INF (Please check the screenshot(project structure)

 

<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
        <property name="hibernate.connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="connection.pool_size">1</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">create-drop</property>
        <mapping class="com.hibernate.manytomany.Employee"/>
        <mapping class="com.hibernate.manytomany.Event"/>
    </session-factory>
</hibernate-configuration>

 

 

 

Project Structure

 

Now project structure looks like following

 

Hibernate Many To Many Mapping Example

 

Just execute below class and see the output

 

HibernateManyToManyExample.java

 

package com.hibernate.manytomany;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.hibernate.manytomany.Event;
import com.hibernate.manytomany.Employee;

public class HibernateManyToManyExample {
    
public static void main(String[] args) {
        
Session session = HibernateUtil.createSessionFactory().openSession();
        Transaction transaction = 
null;
        
try {

            
transaction = session.beginTransaction();
           
            Event event1 = 
new Event("Quaterly Sales meeting");
            Event event2 = 
new Event("Weekly Status meeting");
           
            Employee employee1 = 
new Employee("Rockey");
            Employee employee2 = 
new Employee("Jose");
           
            employee1.getEvents
().add(event1);
            employee1.getEvents
().add(event2);
           
            employee2.getEvents
().add(event1);
            employee2.getEvents
().add(event2);
           
            session.save
(employee1);
            session.save
(employee2);
           
            transaction.commit
();

        
catch (HibernateException e) {
            
transaction.rollback();
            e.printStackTrace
();
        
finally {
            
session.close();
        
}
    }
}

 

Output

 

EMPLOYEEID EMPLOYEENAME
1 Rockey
2 Jose
EMPLOYEEID EVENTID
1 1
2 1
1 2
2 2
EVENTID EVENTNAME
1 Weekly Status Meeting
2 Quaterly Sales Meeting

 

Useful Resources:

 

Hibernate Many to Many Relationship

 

Hibernate Official

arrow
arrow
    全站熱搜

    saravanagumar 發表在 痞客邦 留言(0) 人氣()