Postgres中的GeneratedValue [英] GeneratedValue in Postgres

查看:126
本文介绍了Postgres中的GeneratedValue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  @Entity 
@Audited
@Table (name =messages_locale)
public class Locale {

@Id
@GeneratedValue
@Getter @Setter //项目Lombok的注释,等同于生成的getter和setter方法
private int id;
(...)

我创建干净的新数据库和属性:


< prop key =hibernate.hbm2ddl.auto> create< / b>

在创建数据库之后,为什么会这样(对不起,这个bug几乎浪费了两天) postgres db?:

  CREATE SEQUENCE hibernate_sequence 
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 2
CACHE 1;
ALTER TABLE hibernate_sequence
OWNER TO postgres;

我不想要序列,我想只自动增加自动生成的值.. <在PostgreSQL中,自动增量是通过使用 SERIAL 伪类型来处理的。 在执行 CREATE TABLE 时使用此类型。

现在,这个 SERIAL 伪类型创建一个序列。
使用创建的序列处理 PostgreSQL 中的自动增量。 id 列的默认值为 - nextval('your_sequence_name')



在Hibernate中为用户实体:

  @Id 
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator =users_seq_gen)
@SequenceGenerator(name =users_seq_gen,sequenceName =users_id_seq)
public Long getId() {
return id;

请阅读此处:



http://www.postgresql.org/docs/8.4/static/ datatype-numeric.html#DATATYPE-SERIAL



http ://www.neilconway.org/docs/sequences/


I have my entity class mapped like below:

@Entity
@Audited
@Table(name="messages_locale")
public class Locale {

    @Id
    @GeneratedValue
    @Getter @Setter //Project Lombok's annotations, equal to generated getter and setter method
    private int id;
        (...)

I create clean new database ,and properties:

< prop key="hibernate.hbm2ddl.auto" >create < /prop>

WHY THE HELL (Sorry, almost two days wasted on this bug) after created database, i got a sequence in my postgres db?:

CREATE SEQUENCE hibernate_sequence
  INCREMENT 1
  MINVALUE 1
  MAXVALUE 9223372036854775807
  START 2
  CACHE 1;
ALTER TABLE hibernate_sequence
  OWNER TO postgres;

I dont want to have a sequence, I want to have just auto increment auto generated values..

解决方案

In PostgreSQL auto-increment is handled using the SERIAL pseudo type. You use this type when you execute CREATE TABLE.

Now to the point - this SERIAL pseudo type creates a sequence. Autoincrement in PostgreSQL is handled using the created sequence. The default value of the id column becomes - nextval('your_sequence_name').

In Hibernate for an User entity:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "users_seq_gen")
@SequenceGenerator(name = "users_seq_gen", sequenceName = "users_id_seq")
public Long getId() {
     return id;
}

Read here:

http://www.postgresql.org/docs/8.4/static/datatype-numeric.html#DATATYPE-SERIAL

http://www.neilconway.org/docs/sequences/

这篇关于Postgres中的GeneratedValue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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