手动更新用于在Hibernate中生成主键的计数器? [英] Manually update the counter used for generation of primary key in Hibernate?

查看:91
本文介绍了手动更新用于在Hibernate中生成主键的计数器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的spring项目中,数据库中的表是由Hibernate使用我的实体类作为基础自动创建的,但我手动在表中插入了一些默认值(使用pgAdmin3)。


$ b $因此,我现在面临这个问题:当我尝试通过Java代码在其中一个已经有值的表中插入一个值时,我收到一条错误消息,说主键已经存在于数据库中。 / p>

任何人都知道如何解决这个问题?

UPDATE



这就是我在我的课程中声明我的主键的方式:

  @Id 
@Column(name =id)
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;


解决方案

为每个表调用一次SQL查询来设置序列到下一个空闲数字:

  SELECT setval('tblname_id_seq',max(id))FROM tblname; 

tblname 是表格的实际名称。

Hibernate可能会使用不同的命名约定,或者序列可能已被重命名。如果您无法找到 serial 列,请使用( per documentation ):

pre $ SELECT $ pg_get_serial_sequence(tblname, column_name)

更多详情:

修改Django AutoField开始值


In my spring project, the tables in database are created automatically by Hibernate using my entity classes as base, but I insert some default values in the table manually (using pgAdmin3).

Because that, I am facing now this problem: when I try insert a value via Java code in one of the tables which already have values, I receive a error message, saying the primary key already exists in the database.

Anyone knows how to solve this problem?

UPDATE

That's how I declare my primary key in my class:

@Id
@Column(name = "id")
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;

解决方案

Call this SQL query once per table to set the sequence to the next free number:

SELECT setval('tblname_id_seq', max(id)) FROM tblname;

tblname being the actual name of the table.

Hibernate may use a different naming convention, or the sequence may have been renamed. If you can't find the sequence behind the serial column, check with (per documentation):

SELECT pg_get_serial_sequence(tblname, column_name)

More details:
Modify Django AutoField start value
How to import a CSV to postgresql that already has ID's assigned?

这篇关于手动更新用于在Hibernate中生成主键的计数器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆