Java Libraries
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 Database
Create a database with the name is hibernate5. This database have a table: Employee table.
--
-- Table structure for table `employee`
--
CREATE TABLE `employee` (
`id` varchar(250) NOT NULL,
`name` varchar(250) NOT NULL,
`gender` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `employee`
--
INSERT INTO `employee` (`id`, `name`, `gender`) VALUES ('2017-10-23-10-30-25', 'Employee 1', 'male');
INSERT INTO `employee` (`id`, `name`, `gender`) VALUES ('2017-10-23-10-32-42', 'Employee 2', 'female');
Structures of Employee Table
Student Table
Create Custom Id Generator
Create a class EmployeeIdGenerator.java to create employee’s id from current date and time
EmployeeIdGenerator.java
package id_generation;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.hibernate.*;
import org.hibernate.engine.spi.*;
import org.hibernate.id.*;
public class EmployeeIdGenerator implements IdentifierGenerator {
@Override
public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-MM-mm-ss");
return simpleDateFormat.format(new Date());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Entities Class
Create a entity class – Employee.java to represent the above table
Employee.java
package entities;
import javax.persistence.*;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name = "employee")
public class Employee implements java.io.Serializable {
@Id
@GenericGenerator(name = "sequence_emp_id", strategy = "id_generation.EmployeeIdGenerator")
@GeneratedValue(generator = "sequence_emp_id")
private String id;
@Column
private String name;
@Column
private String gender;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
Hibernate Configuration File
Puts Student.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" />
</session-factory>
</hibernate-configuration>
Create HibernateUtil class
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 id_generation;
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;
}
}
Create EmployeeModel class
The EmployeeModel class contains methods to interact with the database.
package id_generation;
import java.util.List;
import org.hibernate.*;
import entities.*;
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;
}
public List<Employee> findAll() {
List<Employee> employees = null;
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
org.hibernate.query.Query query = session.createQuery("from Employee");
employees = query.getResultList();
transaction.commit();
} catch (Exception e) {
employees = null;
if (transaction != null) {
transaction.rollback();
}
} finally {
session.close();
}
return employees;
}
public Employee findById(String id) {
Employee employee = null;
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
org.hibernate.query.Query query = session.createQuery("from Employee where id = :id");
query.setParameter("id", id);
employee = (Employee) query.uniqueResult();
transaction.commit();
} catch (Exception e) {
employee = null;
if (transaction != null) {
transaction.rollback();
}
} finally {
session.close();
}
return employee;
}
}
Run It
package id_generation;
import entities.Employee;
public class Main {
public static void main(String[] args) {
EmployeeModel employeeModel = new EmployeeModel();
System.out.println("Add New Employee");
Employee newEmployee = new Employee();
newEmployee.setName("Employee 3");
newEmployee.setGender("male");
System.out.println(employeeModel.create(newEmployee));
System.out.println("List All Employee");
for(Employee employee : employeeModel.findAll()) {
System.out.println("Id: " + employee.getId());
System.out.println("Name: " + employee.getName());
System.out.println("Gender: " + employee.getGender());
System.out.println("==================");
}
System.out.println("Find Employee By Id");
Employee employeeInfo = employeeModel.findById("2017-10-23-10-32-42");
System.out.println("Id: " + employeeInfo.getId());
System.out.println("Name: " + employeeInfo.getName());
System.out.println("Gender: " + employeeInfo.getGender());
}
}
Output
Add New Employee
true
List All Employee
Id: 2017-10-23-10-30-25
Name: Employee 1
Gender: male
==================
Id: 2017-10-23-10-32-42
Name: Employee 2
Gender: female
==================
Id: 2017-12-07-12-18-19
Name: Employee 3
Gender: male
==================
Find Employee By Id
Id: 2017-10-23-10-32-42
Name: Employee 2
Gender: female