Use UUID Generator 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 a table: Student table.

--
-- Table structure for table `student`
--

CREATE TABLE `student` (
  `id` binary(16) NOT NULL,
  `name` varchar(250) NOT NULL,
  `email` varchar(250) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `student`
--

INSERT INTO `student` (`id`, `name`, `email`) VALUES
(0xa77df760507d40b5a6d341b2d1eb3ead, 'Student 2', 'student1@gmail.com');

INSERT INTO `student` (`id`, `name`, `email`) VALUES(0x72f792c710bf430e9e07be4f8b29b71e, 'Student 1', 'student1@gmail.com');

INSERT INTO `student` (`id`, `name`, `email`) VALUES(0x04c8a9da59e54228a3383c0108037551, 'Student 3', 'student1@gmail.com');

Structures of Student Table

Student Table




Create a entity class – Student.java to represent the above table

Student.java

package entities;

import java.util.UUID;
import javax.persistence.*;
import org.hibernate.annotations.GenericGenerator;

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

	@Id
	@GenericGenerator(name = "uuid2", strategy = "uuid2")
	@GeneratedValue(generator = "uuid2")
	private UUID id;

	@Column
	private String name;

	@Column
	private String email;

	public UUID getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

}

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.Student" />
	</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 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;

	}
}




The StudentModel class contains methods to interact with the database.

package id_generation;

import java.util.List;
import java.util.UUID;
import org.hibernate.*;
import entities.*;

public class StudentModel {

	private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

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

	public List<Student> findAll() {
		List<Student> students = null;
		Session session = null;
		Transaction transaction = null;
		try {
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();
			org.hibernate.query.Query query = session.createQuery("from Student");
			students = query.getResultList();
			transaction.commit();
		} catch (Exception e) {
			students = null;
			if (transaction != null) {
				transaction.rollback();
			}
		} finally {
			session.close();
		}
		return students;
	}

	public Student findById(UUID id) {
		Student student = null;
		Session session = null;
		Transaction transaction = null;
		try {
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();
			org.hibernate.query.Query query = session.createQuery("from Student where id = :id");
			query.setParameter("id", id);
			student = (Student) query.uniqueResult();
			transaction.commit();
		} catch (Exception e) {
			student = null;
			if (transaction != null) {
				transaction.rollback();
			}
		} finally {
			session.close();
		}
		return student;
	}

}
package id_generation;

import java.util.UUID;
import entities.Student;

public class Main {

	public static void main(String[] args) {

		StudentModel studentModel = new StudentModel();

		System.out.println("Add New Student");
		Student newStudent = new Student();
		newStudent.setId(UUID.randomUUID());
		newStudent.setName("Student 4");
		newStudent.setEmail("student1@gmail.com");
		System.out.println(studentModel.create(newStudent));

		System.out.println("List All Student");
		for(Student student : studentModel.findAll()) {
			System.out.println("Id: " + student.getId());
			System.out.println("Name: " + student.getName());
			System.out.println("Email: " + student.getEmail());
			System.out.println("==================");
		}

		System.out.println("Find Student By Id");
		Student studentInfo = studentModel.findById(UUID.fromString("a77df760-507d-40b5-a6d3-41b2d1eb3ead"));
		System.out.println("Id: " + studentInfo.getId());
		System.out.println("Name: " + studentInfo.getName());
		System.out.println("Email: " + studentInfo.getEmail());


	}

}




Add New Student
true

List All Student
Id: a77df760-507d-40b5-a6d3-41b2d1eb3ead
Name: Student 2
Email: student1@gmail.com
==================
Id: 72f792c7-10bf-430e-9e07-be4f8b29b71e
Name: Student 1
Email: student1@gmail.com
==================
Id: 04c8a9da-59e5-4228-a338-3c0108037551
Name: Student 3
Email: student1@gmail.com
==================
Id: 4295ed9e-4f3f-4109-9905-8666d5b65019
Name: Student 4
Email: student1@gmail.com
==================

Find Student By Id
Id: a77df760-507d-40b5-a6d3-41b2d1eb3ead
Name: Student 2
Email: student1@gmail.com