Hibernate JPA Many To Many Relation Mapping Example
Create Employee & Event model classes as per the above table structure
Employee.java
package com.jpa.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;
}
}
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.jpa.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;
}
}
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.
EntityManagerUtil.java
package com.jpa.manytomany;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class EntityManagerUtil {
private static final EntityManagerFactory entityManagerFactory;
static {
try {
entityManagerFactory = Persistence.createEntityManagerFactory("test");
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static EntityManager getEntityManager() {
return entityManagerFactory.createEntityManager();
}
}
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class EntityManagerUtil {
private static final EntityManagerFactory entityManagerFactory;
static {
try {
entityManagerFactory = Persistence.createEntityManagerFactory("test");
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static EntityManager getEntityManager() {
return entityManagerFactory.createEntityManager();
}
}
persistence.xml
persistence.xml file must be under src/META-INF (Please check the screenshot(project structure)
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"> <persistence-unit name="test" transaction-type="RESOURCE_LOCAL"> <properties> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" /> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test" /> <property name="javax.persistence.jdbc.user" value="root" /> <property name="javax.persistence.jdbc.password" value="root" /> <property name="hibernate.hbm2ddl.auto" value="create-drop" /> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" /> </properties> </persistence-unit> </persistence>