使用 Hibernate 注释映射 PostgreSQL 串行类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4979746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 22:49:44  来源:igfitidea点击:

Mapping PostgreSQL serial type with Hibernate annotations

hibernatepostgresqlsequenceauto-increment

提问by alecswan

I am using Hibernate 3.3 and PostgreSQL 8.x and would like to use Hibernate annotations to map an auto-incremented column which is NOT a primary key.

我正在使用 Hibernate 3.3 和 PostgreSQL 8.x,并想使用 Hibernate 注释来映射一个不是主键的自动递增列。

It doesn't matter if the column is mapped using SERIAL type or sequences in Postgres as long as it gets auto-incremented by the database and not by Hibernate. I tried the following mappings, but they always generated null orderId.

列是否使用 SERIAL 类型或 Postgres 中的序列映射并不重要,只要它由数据库而不是 Hibernate 自动递增即可。我尝试了以下映射,但它们总是生成空 orderId。

@Column(name = "orderId", insertable = false)
@Generated(GenerationTime.INSERT)
//@GeneratedValue(strategy = javax.persistence.GenerationType.AUTO)
private Integer orderId;

I will appreciate any help with this.

我将不胜感激。

Thanks

谢谢

回答by axtavt

The following mapping should work fine:

以下映射应该可以正常工作:

@Column(name = "orderId")
@Generated(GenerationTime.INSERT)
private Integer orderId;

Note, however, that generated value for freshly saved objects is not available until session is flushed.

但是请注意,在刷新会话之前,新保存的对象的生成值不可用。

EDIT:Note that this mapping doesn't affect doesn't make Hibernate to create a column of type serialduring schema generation, since Hibernate doesn't know anything about the nature of value generation at the database side. Therefore, if you want Hibernate to create a column with a proper type, you need to specifiy it explicitly:

编辑:请注意,此映射不会影响不会使 Hibernateserial在模式生成期间创建类型的列,因为 Hibernate 对数据库端的值生成的性质一无所知。因此,如果您希望 Hibernate 创建具有适当类型的列,则需要明确指定它:

@Column(name = "orderId", columnDefinition = "serial")
@Generated(GenerationTime.INSERT)
private Integer orderId;

And on a recent Hibernate version (4.3), you can use this:

在最近的 Hibernate 版本 (4.3) 上,您可以使用以下命令:

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long orderId;

回答by pstanton

the accepted answer doesn't work for me.

接受的答案对我不起作用。

this did though:

虽然这样做了:

@Id
@Column(name = "your_id", columnDefinition = "serial")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer yourId;

回答by bjonczy

I'm using this with postgresql9.1, should work with 8 too:

我将它与 postgresql9.1 一起使用,也应该与 8 一起使用:

@SequenceGenerator(allocationSize=1, initialValue=1, sequenceName="account_id_seq", name="account_id_seq")
@GeneratedValue(generator="account_id_seq", strategy=GenerationType.SEQUENCE)
@Id
@Column(name="id")
private Integer id;