使用 Hibernate 注释映射 PostgreSQL 串行类型 [英] Mapping PostgreSQL serial type with Hibernate annotations

查看:30
本文介绍了使用 Hibernate 注释映射 PostgreSQL 串行类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

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

对于这方面的任何帮助,我将不胜感激.

I will appreciate any help with this.

谢谢

推荐答案

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

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.

请注意,此映射不会影响不会使 Hibernate 在模式生成期间创建 serial 类型的列,因为 Hibernate 不知道任何事情关于数据库端值生成的性质.因此,如果您希望 Hibernate 创建具有适当类型的列,则需要明确指定它:

Note that this mapping doesn't affect doesn't make Hibernate to create a column of type serial during 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:

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

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

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

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

这篇关于使用 Hibernate 注释映射 PostgreSQL 串行类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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