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

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

问题描述

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

只要数据库自动递增,而不是Hibernate自动递增,使用SERIAL类型或Postgres序列映射列是没有关系的。

  @Column(name =orderId,insertable = false)我试过以下映射,但它们总是生成null orderId。 
@Generated(GenerationTime.INSERT)
// @ GeneratedValue(strategy = javax.persistence.GenerationType.AUTO)
private Integer orderId;

我会很感激这方面的帮助。



感谢

解决方案

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

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

但是,请注意,直到会话刷新后,新保存的对象的生成值才可用。注意,这个映射不会影响不会让Hibernate创建一个类型为的串行序列。 在模式生成过程中,因为Hibernate不知道数据库端的值生成性质。因此,如果你希望Hibernate创建一个适当类型的列,你需要明确指定它:

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

在最近的Hibernate版本(4.3)中,可以使用这个:

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


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.

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.

Thanks

解决方案

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 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;

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天全站免登陆