Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

Here is my pojo class

@Entity  public class Department {   @Id @GeneratedValue(strategy=GenerationType.IDENTITY)  @Column(name="Department_Id")  private Integer deptId;   @Column(name="Department_Name",unique=true,nullable=false) private String deptName;   @Column(name="Department_Description") @NotNull private String deptDesc;    //geters and setters 

What i want is that department_id must be primary key of this Department table and entries for this key must be as DEP0001, DEP0002,DEP0003

like image 688
Gaurav Rajput Avatar asked Jul 01 '15 10:07

Gaurav Rajput


People also ask

Can we create entity in Hibernate without primary key?

Not with Hibernate. It requires a primary key.

How does Hibernate generate primary key?

IDENTITY: Hibernate relies on an auto-incremented database column to generate the primary key, SEQUENCE: Hibernate requests the primary key value from a database sequence, TABLE: Hibernate uses a database table to simulate a sequence.

How would you implement a custom sequence based id generator?

If you want to use a custom generator, you need to define the generator in a @GenericGenerator annotation and provide the fully-qualified classname as the strategy. You can also configure a set of parameters that will be provided to the configure method when Hibernate instantiates the generator.

What is primary key in Hibernate annotation?

The primary key class must fulfill several conditions: It should be defined using @EmbeddedId or @IdClass annotations. It should be public, serializable and have a public no-arg constructor. Finally, it should implement equals() and hashCode() methods.

How to use custom generator class in hibernate?

When we need Custom generator class in hibernate : If we want to generate a primary key with our format, then we can go this custom generator, i.e. If we’re going to generate id as numeric, then we can go with any generator except assigned. Or if we want to make the Id as a string type, we can go with assigned.

How to create an employee in hibernate 5?

Create a database with the name is hibernate5. This database have a table: Employee table. Create a class EmployeeIdGenerator.java to create employee’s id from current date and time Create a entity class – Employee.java to represent the above table

Why do we need a hibernate identifier generator?

We need a Hibernate identifier generator that can take any value that we manually assign, and it can also automatically generate a unique identifier when the entity identifier is null. However, the user does not want to use a UUID-like random identifier.

What is the use of the generate method in hibernate?

The generate method gets called when Hibernate needs a primary key value to persist a new entity. The implementation of it is pretty simple. You call the generate method on the superclass to get the next value from the sequence, transform that value into the configured format and add it to the defined prefix.


1 Answers

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;     }  } 
like image 154
Gaurav Rajput Avatar answered Sep 28 '22 11:09

Gaurav Rajput