Create Entity with One to One Mapping in Hibernate 5


Copy JAR files which are listed below:

antlr-2.7.7.jar
classmate-1.3.4.jar
commons-lang3-3.6.jar
commons-logging-1.1.3.jar
dom4j-1.6.1.jar
ehcache-core-2.6.11.jar
geolatte-geom-1.1.0.jar
hibernate-commons-annotations-5.0.1.Final.jar
hibernate-core-5.2.11.Final.jar
hibernate-ehcache-5.2.12.Final.jar
hibernate-ejb3-persistence.jar
hibernate-enhance-maven-plugin-4.3.7.Final.jar
hibernate-entitymanager.jar
hibernate-java8-5.2.11.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
hibernate-spatial-5.2.11.Final.jar
hibernate-validator-6.0.2.Final.jar
javassist-3.16.1-GA.jar
jboss-logging-3.3.1.Final.jar
jboss-transaction-api_1.1_spec-1.0.1.Final.jar
jts-1.11.jar
mysql-connector-java-5.1.36.jar
slf4j-api-1.7.21.jar




Create a database with the name is hibernate5. This database have 2 tables: Employee table and EmployeeCard table. Employee table and EmployeeCard table have a One to One. One employee have one card and One card belongs to one and only one employee.

--
-- Table structure for table `employee`
--

CREATE TABLE `employee` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(250) NOT NULL,
  `password` varchar(250) NOT NULL,
  `status` tinyint(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `employee`
--

INSERT INTO `employee` (`username`, `password`, `status`) VALUES VALUES('e1', '123', 1);
INSERT INTO `employee` (`username`, `password`, `status`) VALUES VALUES('e2', '456', 1);

--
-- Table structure for table `employeecard`
--

CREATE TABLE `employeecard` (
  `employeeId` int(11) NOT NULL PRIMARY KEY,
  `cardNumber` varchar(250) NOT NULL,
  FOREIGN KEY (`employeeId`) REFERENCES `employee` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `employeecard`
--
INSERT INTO `employeecard` (`employeeId`, `cardNumber`) VALUES(1, '111');
INSERT INTO `employeecard` (`employeeId`, `cardNumber`) VALUES(2, '222');

Structure of Employee Table

Employee Table

Structure of Employee Card Table

Employee Card Table

Create two entities classes – Employee.java and EmployeeCard.java, to represent the above tables

Employee.java

package entities;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name = "employee")
public class Employee implements java.io.Serializable {

	private Integer id;
	private String username;
	private String password;
	private boolean status;
	private EmployeeCard employeecard;

	public Employee() {
	}

	public Employee(String username, String password, boolean status) {
		this.username = username;
		this.password = password;
		this.status = status;
	}

	public Employee(String username, String password, boolean status, EmployeeCard employeecard) {
		this.username = username;
		this.password = password;
		this.status = status;
		this.employeecard = employeecard;
	}

	@Id
	@GeneratedValue(strategy = IDENTITY)
	@Column(name = "id", unique = true, nullable = false)
	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	@Column(name = "username", nullable = false, length = 250)
	public String getUsername() {
		return this.username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	@Column(name = "password", nullable = false, length = 250)
	public String getPassword() {
		return this.password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Column(name = "status", nullable = false)
	public boolean isStatus() {
		return this.status;
	}

	public void setStatus(boolean status) {
		this.status = status;
	}

	@OneToOne(fetch = FetchType.LAZY, mappedBy = "employee", cascade = CascadeType.ALL)
	public EmployeeCard getEmployeecard() {
		return this.employeecard;
	}

	public void setEmployeecard(EmployeeCard employeecard) {
		this.employeecard = employeecard;
	}

}

EmployeeCard.java

package entities;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

@Entity
@Table(name = "employeecard")
public class EmployeeCard implements java.io.Serializable {

	private int employeeId;
	private Employee employee;
	private String cardNumber;

	public EmployeeCard() {
	}

	public EmployeeCard(Employee employee, String cardNumber) {
		this.employee = employee;
		this.cardNumber = cardNumber;
	}

	@GenericGenerator(name = "generator", strategy = "foreign", parameters = @Parameter(name = "property", value = "employee"))
	@Id
	@GeneratedValue(generator = "generator")

	@Column(name = "employeeId", unique = true, nullable = false)
	public int getEmployeeId() {
		return this.employeeId;
	}

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

	@OneToOne(fetch = FetchType.LAZY)
	@PrimaryKeyJoinColumn
	public Employee getEmployee() {
		return this.employee;
	}

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

	@Column(name = "cardNumber", nullable = false, length = 250)
	public String getCardNumber() {
		return this.cardNumber;
	}

	public void setCardNumber(String cardNumber) {
		this.cardNumber = cardNumber;
	}

}




Hibernate Configuration File

Puts Employee.java and EmployeeCard.java in your Hibernate configuration file, and also MySQL connection details.

<?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.enable_lazy_load_no_trans">true</property>
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.password">123456</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate5</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.dialect">org.hibernate.spatial.dialect.mysql.MySQLSpatialDialect</property>
		<property name="hibernate.current_session_context_class">thread</property>
		<mapping class="entities.Employee" />
		<mapping class="entities.EmployeeCard" />
	</session-factory>
</hibernate-configuration>

The HibernateUtil class helps in creating the SessionFactory from the Hibernate configuration file. The SessionFactory is threadsafe, so it is not necessary to obtain one for each thread.

package onetoone;

import org.hibernate.*;
import org.hibernate.boot.*;
import org.hibernate.boot.registry.*;

public class HibernateUtil {

	private static final SessionFactory sessionFactory;

	static {
		try {
			StandardServiceRegistry standardRegistry = new
					StandardServiceRegistryBuilder()
					.configure("hibernate.cfg.xml")
					.build();
			Metadata metaData = new MetadataSources(
					standardRegistry)
					.getMetadataBuilder()
					.build();
			sessionFactory = metaData.getSessionFactoryBuilder().build();
		} catch (Throwable th) {
			throw new ExceptionInInitializerError(th);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;

	}
}

The EmployeeModel class contains methods to interact with the database.

package onetoone;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import entities.Employee;

public class EmployeeModel {

	private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

	public boolean create(Employee employee) {
		boolean result = true;
		Session session = null;
		Transaction transaction = null;
		try {
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();
			session.save(employee);
			transaction.commit();
		} catch (Exception e) {
			result = false;
			if (transaction != null) {
				transaction.rollback();
			}
		} finally {
			session.close();
		}
		return result;
	}

}
package onetoone;

import entities.Employee;
import entities.EmployeeCard;

public class Main {

	public static void main(String[] args) {

		EmployeeModel employeeModel = new EmployeeModel();

		System.out.println("Add New Employee");
		Employee employee = new Employee();
		employee.setUsername("e3");
		employee.setPassword("123");
		employee.setStatus(true);
		EmployeeCard employeeCard = new EmployeeCard();
		employeeCard.setCardNumber("777");
		employee.setEmployeeCard(employeeCard);
		employeeCard.setEmployee(employee);
		System.out.println(employeeModel.create(employee));

	}

}




Add New Employee
true

Employee Table

EmployeeCard Table