How to Choose the Id Generation Strategy When Using JPA and Hibernate

Hibernate JPA Generate id

  1. puid has default value 0, when an object is just created.
  2. Hibernate thinks that you set puid value manually, Hibernate doesn't change it.
    Just change long to Long to have null initial value.
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long puid;

Hibernate, what is the most efficient id generation strategy?

The best id generators in Hibernate are enhanced-table and enhanced-sequence, coupled with an appropriate optimizer, such as hilo. I have experience with enhanced-table + hilo, inserting over 10,000 records per second.

BTW the statement that "hilo needs an additional query per generated entity" is patently false: the whole point of the optimizer is to prevent this.

How to generate Custom Id using hibernate while it must be primary key of table

Thank you everyone for your response......
finally i have done some changes in my Department class and used a class for generating ids........Here is my code

@Entity
public class Department {

@Id
@GenericGenerator(name = "sequence_dep_id", strategy = "com.xyz.ids.DepartmentIdGenerator")
@GeneratedValue(generator = "sequence_dep_id")
@Column(name="Department_Id")
private String deptId;

@Column(name="Department_Name",unique=true,nullable=false)
private String deptName;

@Column(name="Department_Description")
@NotNull
private String deptDesc;

//getters and setters

DepartmentIdGenerator.java

package com.xyz.ids;

import java.io.Serializable;
import java.sql.*;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.IdentifierGenerator;

public class DepartmentIdGenerator implements IdentifierGenerator{

@Override
public Serializable generate(SessionImplementor session, Object object)
throws HibernateException {

String prefix = "DEP";
Connection connection = session.connection();

try {
Statement statement=connection.createStatement();

ResultSet rs=statement.executeQuery("select count(Department_Id) as Id from demo.Department");

if(rs.next())
{
int id=rs.getInt(1)+101;
String generatedId = prefix + new Integer(id).toString();
System.out.println("Generated Id: " + generatedId);
return generatedId;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return null;
}

}

How to provide Initial value OR Increment ID with JPA GenerationType.AUTO

I tried various options in answers provided here and for similar questions on stackoverflow and other forums,

I had few limitations,

  1. I couldn't create database sequence as my database changes were freezed.
  2. I didn't want to introduce new Custom IdGenerator class because it would add confusion to other people working with me.

It was resolved using following change:

Adding GenericGenerator with increment strategy helped me, I made following changes to my code.

@Entity
@Table(name = "MY_TABLE")
public class MyEntity {

@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator="seq")
@GenericGenerator(name = "seq", strategy="increment")
@Column(name = "MY_TABLE_ID")
private Integer myTableId;

@Column(name = "MY_TABLE_NM")
private String myTableName;

//Getters Setters
}

It helped me because,
From Hiberbate DOCs

increment

An IdentifierGenerator that returns a long, constructed by counting
from the maximum primary key value at startup. Not safe for use in a
cluster!

Since, it was incrementing already existing myTableId even if it was manually inserted, this resolved my issue.

what is the use of annotations @Id and @GeneratedValue(strategy = GenerationType.IDENTITY)? Why the generationtype is identity?

First of all, using annotations as our configure method is just a convenient method instead of coping the endless XML configuration file.

The @Idannotation is inherited from javax.persistence.Id, indicating the member field below is the primary key of current entity. Hence your Hibernate and spring framework as well as you can do some reflect works based on this annotation. for details please check javadoc for Id

The @GeneratedValue annotation is to configure the way of increment of the specified column(field). For example when using Mysql, you may specify auto_increment in the definition of table to make it self-incremental, and then use

@GeneratedValue(strategy = GenerationType.IDENTITY)

in the Java code to denote that you also acknowledged to use this database server side strategy. Also, you may change the value in this annotation to fit different requirements.

1. Define Sequence in database

For instance, Oracle has to use sequence as increment method, say we create a sequence in Oracle:

create sequence oracle_seq;

2. Refer the database sequence

Now that we have the sequence in database, but we need to establish the relation between Java and DB, by using @SequenceGenerator:

@SequenceGenerator(name="seq",sequenceName="oracle_seq")

sequenceName is the real name of a sequence in Oracle, name is what you want to call it in Java. You need to specify sequenceName if it is different from name, otherwise just use name. I usually ignore sequenceName to save my time.

3. Use sequence in Java

Finally, it is time to make use this sequence in Java. Just add @GeneratedValue:

@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq")

The generator field refers to which sequence generator you want to use. Notice it is not the real sequence name in DB, but the name you specified in name field of SequenceGenerator.

4. Complete

So the complete version should be like this:

public class MyTable
{
@Id
@SequenceGenerator(name="seq",sequenceName="oracle_seq")
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq")
private Integer pid;
}

Now start using these annotations to make your JavaWeb development easier.



Related Topics



Leave a reply



Submit