I am creating an Entity in Hibernate and using @TableGenerator for generating Primary key values. My Entity class is given below:
@Entity
@Table(name="studenttable")
public class Student {
@TableGenerator(
name="stdGen",
table="ID_GEN",
pkColumnValue="studentId",
pkColumnName="GEN_KEY",
valueColumnName="GEN_VALUE", allocationSize = 10)
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "stdGen")
private int studentId;
//rest of the code
}
My question is when I execute the code, initially two times insertion happens ID_GEN table. The console shows like this
Hibernate: select tbl.GEN_VALUE from ID_GEN tbl where tbl.GEN_KEY=? for update
Hibernate: insert into ID_GEN (GEN_KEY, GEN_VALUE) values (?,?)
Hibernate: update ID_GEN set GEN_VALUE=? where GEN_VALUE=? and GEN_KEY=?
Hibernate: select tbl.GEN_VALUE from ID_GEN tbl where tbl.GEN_KEY=? for update
Hibernate: update ID_GEN set GEN_VALUE=? where GEN_VALUE=? and GEN_KEY=?
Please explain why it is happening like this. After that it is working fine. I am writing the below code to insert two objects in the table.
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sessionFactory = cfg.buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.insert(new Student("ABC"));
session.insert(new Student("DEF"));
session.getTransaction().commit();
Using Hibernate 5.2.3 version.