Posted In: Hibernate

Hibernate 5 – @GenericGenerator hilo_seqeunce


From Hibernate user guide
hilo; legacy-hilo
Define a custom algorithm for generating pools of values based on a single value from a table or sequence.
These optimizers are not recommended for use. They are maintained (and mentioned) here simply for use by legacy applications that used these strategies previously.

@GenericGenerator(name = "hilo_sequence_generator",
	strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
	parameters = {
			@Parameter(name = "sequence_name", value = "hilo_seqeunce"),
			@Parameter(name = "initial_value", value = "1"),
			@Parameter(name = "increment_size", value = "3"),
			@Parameter(name = "optimizer", value = "hilo") })

First generated ID is 1 which is initial_value
Then generated ID increments by 3 and then by one

Hibernate: insert into employer_master (EMPLOYER_ADDRESS, EMPLOYER_NM, EMPLOYER_ID) values (?, ?, ?)
23:46:27,979 TRACE BasicBinder:65 - binding parameter [1] as [VARCHAR] - [Bengaluru]
23:46:27,979 TRACE BasicBinder:65 - binding parameter [2] as [VARCHAR] - [INFOSYS]
23:46:27,979 TRACE BasicBinder:65 - binding parameter [3] as [BIGINT] - [1]
Hibernate: insert into employee_master (EMPLOYER_ID, FIRST_NM, LAST_NM, MIDLLE_NM, EMPLOYEE_ID) values (?, ?, ?, ?, ?)
23:46:27,979 TRACE BasicBinder:65 - binding parameter [1] as [BIGINT] - [1]
23:46:27,979 TRACE BasicBinder:65 - binding parameter [2] as [VARCHAR] - [Abhijit]
23:46:27,979 TRACE BasicBinder:65 - binding parameter [3] as [VARCHAR] - [Pednekar]
23:46:27,979 TRACE BasicBinder:53 - binding parameter [4] as [VARCHAR] - [null]
23:46:27,979 TRACE BasicBinder:65 - binding parameter [5] as [BIGINT] - [4]
.....
.....
.....
Hibernate: insert into employee_master (EMPLOYER_ID, FIRST_NM, LAST_NM, MIDLLE_NM, EMPLOYEE_ID) values (?, ?, ?, ?, ?)
23:46:28,387 TRACE BasicBinder:65 - binding parameter [1] as [BIGINT] - [1]
23:46:28,387 TRACE BasicBinder:65 - binding parameter [2] as [VARCHAR] - [Abhijit]
23:46:28,387 TRACE BasicBinder:65 - binding parameter [3] as [VARCHAR] - [Pednekar]
23:46:28,387 TRACE BasicBinder:53 - binding parameter [4] as [VARCHAR] - [null]
23:46:28,387 TRACE BasicBinder:65 - binding parameter [5] as [BIGINT] - [103]

 

Maven Hibernate 5.2.5

<dependency>
	<groupId>org.hibernate</groupId>
	<artifactId>hibernate-tools</artifactId>
	<version>5.2.5.Final</version>
</dependency>
<dependency>
	<groupId>org.hibernate</groupId>
	<artifactId>hibernate-core</artifactId>
	<version>5.2.10.Final</version>
</dependency>
<dependency>
	<groupId>org.hibernate</groupId>
	<artifactId>hibernate-entitymanager</artifactId>
	<version>5.2.10.Final</version>
</dependency>
<dependency>
	<groupId>org.hibernate.javax.persistence</groupId>
	<artifactId>hibernate-jpa-2.1-api</artifactId>
	<version>1.0.0.Final</version>
</dependency>
<dependency>
	<groupId>javassist</groupId>
	<artifactId>javassist</artifactId>
	<version>3.12.1.GA</version>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>5.1.43</version>
</dependency>
<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-log4j12</artifactId>
	<version>1.7.25</version>
</dependency>

 

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="connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="connection.url">jdbc:mysql://localhost:3306/new_schema</property>
		<property name="connection.username">root</property>
		<property name="connection.password">password</property>
		<property name="connection.pool_size">10</property>
		<property name="dialect">org.hibernate.dialect.MySQL57Dialect</property>
		<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
		<property name="show_sql">true</property>
		<property name="hbm2ddl.auto">create</property>
		<mapping class="com.example.hibernate.Employee" />
		<mapping class="com.example.hibernate.Employer" />
	</session-factory>
</hibernate-configuration>

 

Employee POJO with @GenericGenerator name = “hilo_sequence_generator”

package com.example.hibernate;

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.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

@Entity
@Table(name = "employee_master")
public class Employee {
	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE,
	        generator = "hilo_sequence_generator")
	@GenericGenerator(name = "hilo_sequence_generator",
	        strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
	        parameters = {
	                @Parameter(name = "sequence_name", value = "hilo_seqeunce"),
	                @Parameter(name = "initial_value", value = "1"),
	                @Parameter(name = "increment_size", value = "3"),
	                @Parameter(name = "optimizer", value = "hilo") })
	@Column(name = "EMPLOYEE_ID")
	private Long employeeId;
	@Column(name = "FIRST_NM", length = 50)
	private String firstName;
	@Column(name = "LAST_NM", length = 50)
	private String lastName;
	@Column(name = "MIDLLE_NM", length = 50)
	private String middleName;

	@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
	@JoinColumn(name = "EMPLOYER_ID", nullable = false)
	private Employer employer;
...............
//getter setter
}

 

Employer POJO with @GenericGenerator name = “hilo_sequence_generator”

package com.example.hibernate;

import java.util.HashSet;
import java.util.Set;

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

import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Parameter;

@Entity
@Table(name = "employer_master",
        uniqueConstraints = { @UniqueConstraint(columnNames = "EMPLOYER_NM") })
public class Employer {
	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE,
	        generator = "hilo_sequence_generator")
	@GenericGenerator(name = "hilo_sequence_generator",
	        strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
	        parameters = {
	                @Parameter(name = "sequence_name", value = "hilo_seqeunce"),
	                @Parameter(name = "initial_value", value = "1"),
	                @Parameter(name = "increment_size", value = "3"),
	                @Parameter(name = "optimizer", value = "hilo") })
	@Column(name = "EMPLOYER_ID")
	private Long employerId;
	@Column(name = "EMPLOYER_NM", length = 50)
	private String employerName;
	@Column(name = "EMPLOYER_ADDRESS", length = 150)
	private String employerAddress;

	@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER,
	        mappedBy = "employer")
	private Set<Employee> employees = new HashSet<Employee>();
...............
//getter setter
}

 

Session creator

package com.example.hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

	private static final SessionFactory sessionFactory = buildSessionFactory();

	private static SessionFactory buildSessionFactory() {

		try {
			Configuration configuration = new Configuration()
			        .configure("hibernate.cfg.xml");
			configuration.addAnnotatedClass(Employee.class);
			configuration.addAnnotatedClass(Employer.class);
			StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
			        .applySettings(configuration.getProperties());
			SessionFactory factory = configuration
			        .buildSessionFactory(builder.build());

			return factory;
		} catch (Throwable ex) {
			ex.printStackTrace();
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}
}

 

Create and save Employer and list of Employees

package com.example.hibernate;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

public class Main {

	public static void main(String[] args) {

		SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
		Session session = sessionFactory.openSession();
		try {

			Employer employer = new Employer();
			employer.setEmployerId(0L);
			employer.setEmployerName("INFOSYS");
			employer.setEmployerAddress("Bengaluru");

			session.beginTransaction();
			session.save(employer);

			for (int i = 0; i < 100; i++) {
				Employee employee = new Employee();
				// employee.setEmployeeId(0L);
				employee.setFirstName("Abhijit");
				employee.setLastName("Pednekar");
				employee.setEmployer(employer);
				session.save(employee);
			}
			session.getTransaction().commit();
			session.close();

			session = sessionFactory.openSession();
			List<Employer> employers = session
			        .createNativeQuery("SELECT * FROM employer_master",
			                Employer.class)
			        .getResultList();
			System.out.println(employers);
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			session.close();
			sessionFactory.close();
		}
	}
}

by , on September 4th, 2017

  • Categories