JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Hibernate Bidirectional One-to-Many mapping using @OneToMany annotation.


In our database we create many tables and many of them may be associated with each other. At higher lever, these associations can be classified into one-to-one, one-to-many and many-to-many. These associations can be either unidirectional or bidirectional mappings. Hibernate provides support to all these associations.

In this page, we see how to implement bidirectional One-to-Many mapping between persisted objects using @OneToMany annotation.

A one-to-many relationship occurs when one entity is related to multiple occurrences of another entity.

Create DB Table

Here is our DB tables. Our tables are already One-to-Many mapped. We have created EMPLOYEES AND ASSET_MNGT tables. EMPLOYEES is our primary table and we are using Foreign Key in ASSET_MNGT table for One-to-Many mapping.

CREATE TABLE EMPLOYEES (

	EMP_ID BIGINT NOT NULL AUTO_INCREMENT,
	NAME VARCHAR(252),
	DEPARTMENT VARCHAR(128),
	SALARY BIGINT,
	JOINED_ON TIMESTAMP,
	PRIMARY KEY (EMP_ID)
);

CREATE TABLE ASSET_MNGT (

	AM_ID BIGINT NOT NULL AUTO_INCREMENT,
	EMP_ID BIGINT,
	ASSET_NAME VARCHAR(128),
	VENDOR VARCHAR(128),
	PRIMARY KEY (AM_ID),
	FOREIGN KEY (EMP_ID) REFERENCES EMPLOYEES(EMP_ID)
);

INSERT INTO EMPLOYEES (EMP_ID, NAME, DEPARTMENT, SALARY, JOINED_ON) VALUES (1, 'Nataraja G', 'Documentation', 10000, CURRENT_TIMESTAMP);
INSERT INTO EMPLOYEES (EMP_ID, NAME, DEPARTMENT, SALARY, JOINED_ON) VALUES (2, 'Amar M', 'Entertainment', 12000, CURRENT_TIMESTAMP);
INSERT INTO EMPLOYEES (EMP_ID, NAME, DEPARTMENT, SALARY, JOINED_ON) VALUES (3, 'Nagesh Y', 'Admin', 25000, CURRENT_TIMESTAMP);
INSERT INTO EMPLOYEES (EMP_ID, NAME, DEPARTMENT, SALARY, JOINED_ON) VALUES (4, 'Vasu V', 'Security', 2500, CURRENT_TIMESTAMP);

INSERT INTO ASSET_MNGT (EMP_ID, ASSET_NAME, VENDOR) VALUES (1, 'Laptop', 'Apple');
INSERT INTO ASSET_MNGT (EMP_ID, ASSET_NAME, VENDOR) VALUES (1, 'Mobile', 'Apple');
INSERT INTO ASSET_MNGT (EMP_ID, ASSET_NAME, VENDOR) VALUES (1, 'LCD Monitor', 'HCL');

INSERT INTO ASSET_MNGT (EMP_ID, ASSET_NAME, VENDOR) VALUES (2, 'Laptop', 'Apple');
INSERT INTO ASSET_MNGT (EMP_ID, ASSET_NAME, VENDOR) VALUES (2, 'Mobile', 'Samsung');
INSERT INTO ASSET_MNGT (EMP_ID, ASSET_NAME, VENDOR) VALUES (2, 'LCD Monitor', 'HCL');

INSERT INTO ASSET_MNGT (EMP_ID, ASSET_NAME, VENDOR) VALUES (3, 'Laptop', 'Apple');
INSERT INTO ASSET_MNGT (EMP_ID, ASSET_NAME, VENDOR) VALUES (3, 'Mobile', 'Samsung');

INSERT INTO ASSET_MNGT (EMP_ID, ASSET_NAME, VENDOR) VALUES (4, 'Laptop', 'Apple');

Hibernate Configuration File

Create hibernate xml based configuration file in your resources folder (classpath). This file includes hibernate configurations like driver class, DB connectivity URL, DB credentials and so on...

j2n-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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/java2novice</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.connection.password">root</property>
		<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
		<property name="show_sql">false</property>
	</session-factory>
</hibernate-configuration>

Hibernate Mapping with Entity Class

Here is the entity classes according to our database tables along with One-to-Many mappings. Since we are creating bidirectional mapping, we have placed @OneToMany annotation in parent entity class and @ManyToOne in child table.

package com.java2novice.model;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="EMPLOYEES")
public class Employee implements Serializable {

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name="EMP_ID", unique = true, nullable = false)
	private Long empId;

	private String name;

	private String department;

	private Long salary;

	@Column(name="JOINED_ON")
	private Date joinedOn;

	@OneToMany(fetch = FetchType.EAGER, mappedBy="employee", cascade = CascadeType.ALL)
	private List<AssetMgnt> assetMgnt;

	public List<AssetMgnt> getAssetMgnt() {
		return assetMgnt;
	}

	public void setAssetMgnt(List<AssetMgnt> assetMgnt) {
		this.assetMgnt = assetMgnt;
	}

	public Long getEmpId() {
		return empId;
	}

	public void setEmpId(Long empId) {
		this.empId = empId;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDepartment() {
		return department;
	}

	public void setDepartment(String department) {
		this.department = department;
	}

	public Long getSalary() {
		return salary;
	}

	public void setSalary(Long salary) {
		this.salary = salary;
	}

	public Date getJoinedOn() {
		return joinedOn;
	}

	public void setJoinedOn(Date joinedOn) {
		this.joinedOn = joinedOn;
	}

	@Override
	public String toString() {

		String resp = this.empId+" | "+this.name+" | "+this.department+" | "+this.salary+" | "+this.joinedOn;

		return resp;
	}
}

package com.java2novice.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="ASSET_MNGT")
public class AssetMgnt implements Serializable{

	@Id
	@GeneratedValue(strategy=GenerationType.IDENTITY)
	@Column(name="AM_ID", unique = true, nullable = false)
	private Long amId;

	@ManyToOne(fetch = FetchType.LAZY)
	@JoinColumn(name="EMP_ID")
	private Employee employee;

	@Column(name="ASSET_NAME")
	private String assetName;

	private String vendor;

	public Long getAmId() {
		return amId;
	}

	public void setAmId(Long amId) {
		this.amId = amId;
	}

	public Employee getEmployee() {
		return employee;
	}

	public void setEmployee(Employee employee) {
		this.employee = employee;
	}

	public String getAssetName() {
		return assetName;
	}

	public void setAssetName(String assetName) {
		this.assetName = assetName;
	}

	public String getVendor() {
		return vendor;
	}

	public void setVendor(String vendor) {
		this.vendor = vendor;
	}

	public String toString() {

		return this.assetName+" | "+this.vendor;
	}
}

Hibernate Utility Class

This class manages hibernate session.

package com.java2novice.hibernate;

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

import com.java2novice.model.AssetMgnt;
import com.java2novice.model.EmpDetails;
import com.java2novice.model.Employee;

public class HibernateUtil {

	private static SessionFactory sessionFactory = null;

	static {
		try{
			loadSessionFactory();
		}catch(Exception e){
			System.err.println("Exception while initializing hibernate util.. ");
			e.printStackTrace();
		}
	}

	public static void loadSessionFactory(){

		Configuration configuration = new Configuration();
		configuration.configure("/j2n-hibernate.cfg.xml");
		configuration.addAnnotatedClass(Employee.class);
		configuration.addAnnotatedClass(EmpDetails.class);
		configuration.addAnnotatedClass(AssetMgnt.class);
		ServiceRegistry srvcReg = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
		sessionFactory = configuration.buildSessionFactory(srvcReg);
	}

	public static Session getSession() throws HibernateException {

		Session retSession=null;
	    	try {
	    		retSession = sessionFactory.openSession();
	    	}catch(Throwable t){
			System.err.println("Exception while getting session.. ");
			t.printStackTrace();
	    	}
	    	if(retSession == null) {
	    		System.err.println("session is discovered null");
	    	}

	    	return retSession;
    }
}

Hibernate Dao Class

package com.java2novice.hibernate;

import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.java2novice.model.Employee;

public class EmployeesDao {

	public List<Employee> getEmployeeList(){

		Session session = null;
		List<Employee> empList = null;
		try {
			session = HibernateUtil.getSession();
			String queryStr = "select emp from Employee emp";
			Query query = session.createQuery(queryStr);
			empList = query.list();
		} catch(Exception ex) {
			ex.printStackTrace();
			// handle exception here
		} finally {
			try {if(session != null) session.close();} catch(Exception ex) {}
		}
		return empList;
	}

	public static void main(String a[]) {

		List<Employee> empList = empDao.getEmployeeList();
		System.out.println("emp size: "+empList.size());
		System.out.println("---------------------------");
		empList.stream().forEach(e -> {
			System.out.println(e);
			System.out.println("-- asset given to "+e.getName()+" --");
			e.getAssetMgnt().stream().forEach(System.out::println);
			System.out.println("---------------------------");
		});
	}
}

Output:
emp size: 4
---------------------------
1 | Nataraja G | Documentation | 10000 | 2017-12-16 11:59:59.0
-- asset given to Nataraja G --
Laptop | Apple
Mobile | Apple
LCD Monitor | HCL
---------------------------
2 | Amar M | Entertainment | 12000 | 2017-12-16 11:59:59.0
-- asset given to Amar M --
Laptop | Apple
Mobile | Samsung
LCD Monitor | HCL
---------------------------
3 | Nagesh Y | Admin | 25000 | 2017-12-16 11:59:59.0
-- asset given to Nagesh Y --
Laptop | Apple
Mobile | Samsung
---------------------------
4 | Vasu V | Security | 2500 | 2017-12-16 12:00:21.0
-- asset given to Vasu V --
Laptop | Apple
---------------------------
<< Previous Program | Next Program >>

Hibernate Examples

  1. Hibernate hello world (initial setup) example.
  2. What is hibernate.cfg.xml configuration?
  3. What are the basic hibernate persistent annotations?
  4. What is SessionFactory in Hibernate?
  5. What is Session object in Hibernate?
  6. List Hibernate Session interface methods.
  7. What is Hibernate Query object?
  8. Basic Hibernate CRUD operations example.
  9. Hibernate Bidirectional One-to-One mapping using @OneToOne annotation.
  10. Hibernate Unidirectional One-to-One mapping using @OneToOne annotation.
  11. Hibernate Eager vs Lazy Fetch Type
  12. Hibernate Unidirectional One-to-Many mapping using @OneToMany annotation.
  13. Hibernate Bidirectional One-to-Many mapping using @OneToMany annotation.
  14. Hibernate Many-to-Many mapping example using @ManyToMany annotation.
  15. How to enable logging (log4j) in Hibernate?
Knowledge Centre
Different types of Access Modifiers
public: Any thing declared as public can be accessed from anywhere.

private: Any thing declared as private can't be seen outside of its class.

protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages.

default modifier: Can be accessed only to classes in the same package.
Famous Quotations
Success consists of going from failure to failure without loss of enthusiasm.
-- Winston Churchill

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2018 by Nataraja Gootooru. All Rights Reserved.