Mapping PostgreSQL serial type with Hibernate annotations

后端 未结 4 1898
北海茫月
北海茫月 2020-12-02 23:13

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 ma

4条回答
  •  感情败类
    2020-12-02 23:45

    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;
    

提交回复
热议问题