Hibernate Many To One Relation Mapping Example
Hibernate Many To One Relation Mapping Example explains about how to implement a Many To One relationship by using Hibernate
many-to-one entity relationship, multiple records of an entity have single record in other associated entity
On this standalone Hibernate Many To One Mapping Example, we are using Hibernate With MySQL Database.
Let us see how to implement many-to-one relationship using Hibernate
Required Libraries
You need to download
Following jar must be in classpath
- antlr-2.7.7.jar
- dom4j-1.6.1.jar
- hibernate-commons-annotations-4.0.4.Final.jar
- hibernate-core-4.3.1.Final.jar
- hibernate-entitymanager-4.3.1.Final.jar
- jandex-1.1.0.Final.jar
- dom4j-1.6.1.jar
- jboss-logging-3.1.3.GA.jar
- hibernate-jpa-2.1-api-1.0.0.Final.jar
- jboss-transaction-api_1.2_spec-1.0.0.Final.jar
- mysql-connector-java-5.1.28-bin.jar
Table structure
CREATE TABLE `company` ( `ADDRESSID` bigint(20) NOT NULL AUTO_INCREMENT, `CITY` varchar(255) DEFAULT NULL, `COUNTRY` varchar(255) DEFAULT NULL, `STATE` varchar(255) DEFAULT NULL, `STREET` varchar(255) DEFAULT NULL, PRIMARY KEY (`ADDRESSID`) ); CREATE TABLE `employee` ( `EMPLOYEEID` bigint(20) NOT NULL AUTO_INCREMENT, `EMPLOYEENAME` varchar(255) DEFAULT NULL, `COMPANY_EMPLOYEE` bigint(20) DEFAULT NULL, PRIMARY KEY (`EMPLOYEEID`), KEY `FK_j1a2fo8yfvds4h8fr03ydga18` (`COMPANY_EMPLOYEE`), CONSTRAINT `FK_j1a2fo8yfvds4h8fr03ydga18` FOREIGN KEY (`COMPANY_EMPLOYEE`) REFERENCES `company` (`ADDRESSID`) ) ;
Create Company & Employee model classes as per the above table structure
Company.java
package com.hibernate.manytoone;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Company implements java.io.Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Column(name = "ADDRESSID")
private long addressID;
@Column(name = "STREET")
private String street;
@Column(name = "CITY")
private String city;
@Column(name = "STATE")
private String state;
@Column(name = "COUNTRY")
private String country;
public Company() {
super();
}
public Company(String street, String city, String state, String country) {
this.street = street;
this.city = city;
this.state = state;
this.country = country;
}
public long getAddressID() {
return addressID;
}
public void setAddressID(long addressID) {
this.addressID = addressID;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class Company implements java.io.Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Column(name = "ADDRESSID")
private long addressID;
@Column(name = "STREET")
private String street;
@Column(name = "CITY")
private String city;
@Column(name = "STATE")
private String state;
@Column(name = "COUNTRY")
private String country;
public Company() {
super();
}
public Company(String street, String city, String state, String country) {
this.street = street;
this.city = city;
this.state = state;
this.country = country;
}
public long getAddressID() {
return addressID;
}
public void setAddressID(long addressID) {
this.addressID = addressID;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
Employee.java
package com.hibernate.manytoone;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@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;
@ManyToOne(cascade = CascadeType.ALL,fetch=FetchType.LAZY)
@JoinColumn(name = "COMPANY_EMPLOYEE")
private Company company;
public Employee() {
super();
}
public Employee(String employeeName) {
super();
this.employeeName = employeeName;
}
public Employee(String employeeName, Company company) {
this.employeeName = employeeName;
this.company = company;
}
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 Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
}
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
@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;
@ManyToOne(cascade = CascadeType.ALL,fetch=FetchType.LAZY)
@JoinColumn(name = "COMPANY_EMPLOYEE")
private Company company;
public Employee() {
super();
}
public Employee(String employeeName) {
super();
this.employeeName = employeeName;
}
public Employee(String employeeName, Company company) {
this.employeeName = employeeName;
this.company = company;
}
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 Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
}
@ManyToOne(cascade = CascadeType.ALL,fetch=FetchType.LAZY) annotation is used for linking multiple records of Company table with single record of Employee table
@JoinColumn(name = "COMPANY_EMPLOYEE") , Here COMPANY_EMPLOYEE is a column which is connecting company & employee tables by using keyword @JoinColumn (COMPANY_EMPLOYEE)
@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.manytoone;
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;
}
}
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)
<?xml version="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.manytoone.Employee"/> <mapping class="com.hibernate.manytoone.Company"/> </session-factory> </hibernate-configuration>
Project Structure
Now project structure looks like following
Just execute below class and see the output
HibernateManyToOneExample.java
package com.hibernate.manytoone;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class HibernateManyToOneExample {
public static void main(String[] args) {
Session session = HibernateUtil.createSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Company company = new Company();
company.setCity("Kolkata");
company.setCountry("India");
company.setState("Bengal");
company.setStreet("Number 15");
Employee employee1 = new Employee("Rockey",company);
Employee employee2 = new Employee("Jose",company);
session.save(employee1);
session.save(employee2);
transaction.commit();
} catch (Exception e) {
transaction.rollback();
}finally {
session.close();
}
}
}
import org.hibernate.Session;
import org.hibernate.Transaction;
public class HibernateManyToOneExample {
public static void main(String[] args) {
Session session = HibernateUtil.createSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
Company company = new Company();
company.setCity("Kolkata");
company.setCountry("India");
company.setState("Bengal");
company.setStreet("Number 15");
Employee employee1 = new Employee("Rockey",company);
Employee employee2 = new Employee("Jose",company);
session.save(employee1);
session.save(employee2);
transaction.commit();
} catch (Exception e) {
transaction.rollback();
}finally {
session.close();
}
}
}
Output
ADDRESSID | CITY | COUNTRY | STATE | STREET |
1 | Kolkata | India | Bengal | Number 15 |
EMPLOYEEID | EMPLOYEENAME | COMPANY_EMPLOYEE |
1 | Rockey | 1 |
2 | Jose | 1 |