JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Hibernate Unidirectional One-to-One mapping using @OneToOne 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 unidirectional One-to-One mapping between persisted objects using @OneToOne annotation.

A one-to-one relationships occurs when one entity is related to exactly one occurrence in another entity.

Create DB Table

Here is our DB tables. Our tables are already One-to-One mapped. We have created EMPLOYEES AND EMP_DETAILS tables. EMPLOYEES is our primary table and we are using Foreign Key in EMP_DETAILS table for One-to-One 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 EMP_DETAILS (

	ED_ID BIGINT NOT NULL AUTO_INCREMENT,
	EMP_ID BIGINT,
	ADDRESS VARCHAR(252),
	GENDER VARCHAR(8),
	YEARS_OF_SERVICE BIGINT,
	BANK_ACCOUNT VARCHAR(128),
	PRIMARY KEY (ED_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 EMP_DETAILS (EMP_ID, ADDRESS, GENDER, YEARS_OF_SERVICE, BANK_ACCOUNT) VALUES (1, 'Bangalore', 'Male', 4, '00343466');
INSERT INTO EMP_DETAILS (EMP_ID, ADDRESS, GENDER, YEARS_OF_SERVICE, BANK_ACCOUNT) VALUES (2, 'Chennai', 'Male', 2, '988800098');
INSERT INTO EMP_DETAILS (EMP_ID, ADDRESS, GENDER, YEARS_OF_SERVICE, BANK_ACCOUNT) VALUES (3, 'Bangalore', 'Male', 6, '11129098');
INSERT INTO EMP_DETAILS (EMP_ID, ADDRESS, GENDER, YEARS_OF_SERVICE, BANK_ACCOUNT) VALUES (4, 'Hyderabad', 'Male', 10, '887639421');

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-One mappings. Since we are creating unidirectional mapping, we have placed @OneToOne annotation only in one entity class.

package com.java2novice.model;

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

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.JoinColumn;
import javax.persistence.OneToOne;
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;

	@OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
	@JoinColumn(name="EMP_ID")
	private EmpDetails empDetails;

	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;
	}

	public EmpDetails getEmpDetails() {
		return empDetails;
	}

	public void setEmpDetails(EmpDetails empDetails) {
		this.empDetails = empDetails;
	}

	@Override
	public String toString() {

		String resp = this.empId+" | "+this.name+" | "+this.department+" | "+this.salary+" | "+this.joinedOn;
		if(this.empDetails != null) {
			resp += "|"+this.empDetails.toString();
		}

		return resp;
	}
}

package com.java2novice.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="EMP_DETAILS")
public class EmpDetails {

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

	private String address;

	private String gender;

	@Column(name="YEARS_OF_SERVICE")
	private Long yearsOfService;

	@Column(name="BANK_ACCOUNT")
	private String bankAccount;

	@Column(name="EMP_ID")
	private Long empId;

	public Long getEdId() {
		return edId;
	}

	public void setEdId(Long edId) {
		this.edId = edId;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public Long getYearsOfService() {
		return yearsOfService;
	}

	public void setYearsOfService(Long yearsOfService) {
		this.yearsOfService = yearsOfService;
	}

	public String getBankAccount() {
		return bankAccount;
	}

	public void setBankAccount(String bankAccount) {
		this.bankAccount = bankAccount;
	}

	public Long getEmpId() {
		return empId;
	}

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

	@Override
	public String toString() {

		return this.gender+" | "+this.address+" | "+this.yearsOfService+" | "+this.bankAccount;
	}
}

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.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);
		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[]) {

		EmployeesDao empDao = new EmployeesDao();
		System.out.println("---------------------------");

		List<Employee> empList = empDao.getEmployeeList();
		System.out.println("emp size: "+empList.size());
		empList.stream().forEach(System.out::println);

		System.out.println("---------------------------");
	}
}

Output:
---------------------------
emp size: 4
1 | Nataraja G | Documentation | 10000 | 2017-12-16 11:59:59.0|Male | Bangalore | 4 | 00343466
2 | Amar M | Entertainment | 12000 | 2017-12-16 11:59:59.0|Male | Chennai | 2 | 988800098
3 | Nagesh Y | Admin | 25000 | 2017-12-16 11:59:59.0|Male | Bangalore | 6 | 11129098
4 | Vasu V | Security | 2500 | 2017-12-16 12:00:21.0|Male | Hyderabad | 10 | 887639421
---------------------------
<< 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
Default value of a local variables?
The local variables are not initialized to any default values. We should not use local variables with out initialization. Even the java compiler throws error.
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 © 2022 by Nataraja Gootooru. All Rights Reserved.