英文:
Hibernate inserting two times in table using @TableGenerator
问题
我正在Hibernate中创建一个实体,并使用@TableGenerator生成主键值。
我的实体类如下:
@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;
//其余代码
}
我的问题是,当我执行代码时,最初会在ID_GEN表中发生两次插入。控制台显示如下:
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=?
请解释为什么会出现这种情况。之后它正常工作。
我正在使用以下代码向表中插入两个对象。
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();
使用Hibernate版本5.2.3。
英文:
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.
专注分享java语言的经验与见解,让所有开发者获益!
评论