如何在数据库表已填充JPA时正确设置@Id字段 [英] How to set up @Id field properly when database table is already populated JPA
问题描述
我在数据库中有一个表,并在字段中添加了 @Id
属性。作为策略
我使用 GenerationType.IDENTITY
。当数据库表尚未填充SQL脚本中的行时,这很正常。
I am having a single table in my database and I have added the @Id
attribute over the field. As strategy
I use GenerationType.IDENTITY
. This works fine WHEN the database table is not already populated by rows from a SQL script.
当表中已有某些行时,如何设置它才能工作它?因为当我尝试在预先填充时从我的应用程序插入实体时它不起作用。
How can I manage to get it to work when the table already has some rows in it? Because it doesn't work when I am trying to insert entities from my application when it is pre-populated.
我正在使用Derby数据库和eclipselink作为实现。
I am using Derby database for this and eclipselink as implementation.
推荐答案
使用序列生成器从序列表中获取其ID。这样的事情:
Use sequence generator that gets its ids from a sequence table. Something like this:
@Id
@GeneratedValue(generator = "yourTableIdGenerator")
@GenericGenerator(name = "yourTableIdGenerator", strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator", parameters = {
@Parameter(name = "sequence_name", value = "your_table_id_seq"),
@Parameter(name = "optimizer", value = "hilo"),
@Parameter(name = "initial_value", value = "1000"),
@Parameter(name = "increment_size", value = "10") }
)
@Column(name = "your_table_id", length = 15)
public Long getId() {
return id;
}
将initial_value设置为大于从中填充的行的最大ID的值脚本。
Set the initial_value to a value larger than the maximum id of the rows populated from the script.
来自java 6 ee api: http://download.oracle.com/javaee/6/api/javax/persistence/TableGenerator.html
From the java 6 ee api: http://download.oracle.com/javaee/6/api/javax/persistence/TableGenerator.html
@TableGenerator(
name="empGen",
table="ID_GEN",
pkColumnName="GEN_KEY",
valueColumnName="GEN_VALUE",
pkColumnValue="EMP_ID",
initialValue = 1000,
allocationSize=1)
@Id
@GeneratedValue(strategy=TABLE, generator="empGen")
int id;
这篇关于如何在数据库表已填充JPA时正确设置@Id字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!