Justin Wrobel
Justin Wrobel

Reputation: 2019

Hibernate: hbm2ddl doesn't set sequence.nextval as column default

I'm running into a problem with mapping sequences to a column's default while using Hibernate's hbm2ddl to generate the database schema. After using hbm2ddl on a fresh database the generated SQL doesn't set a default value on the table. This causes problems when using anything other than Hibernate to issue insert statements.

The following java code details the troublesome entity:

@Entity
@Table(name = "ROLE")
public class Role {

    @Id
    @Column(name = "ROLE_ID")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
    @SequenceGenerator( name = "seq", sequenceName = "SEQ_ROLE_ID", allocationSize=1, initialValue=1)
    public Integer getRoleId() {
        return roleId;
    }

    ...
}

The above generates the following SQL in the following order:

create table ROLE (ROLE_ID integer not null, primary key (ROLE_ID))
create sequence SEQ_ROLE_ID

Issuing an insert through Hibernate works as you'd expect but issuing an insert through SQL (E.G., INSERT INTO "ROLE" (NAME) VALUES ('ADMIN');) results in a NULL not allowed for column "ROLE_ID" error message.

Is there anyway I can get the hbm2ddl to generate the following SQL in the following order?

CREATE SEQUENCE SEQ_ROLE_ID
CREATE TABLE ROLE (ROLE_ID NUMBER DEFAULT SEQ_ROLE_ID.NEXTVAL);

I am using the 4.0.1.Final version of Hibernate and H2 for the database.

Upvotes: 0

Views: 1175

Answers (1)

Dmitriy Korniyko
Dmitriy Korniyko

Reputation: 21

use "schema" in @SequenceGenerator (for example: schema="public" ) and columnDefinition in @Column

    @Id
    @Column(name = "ROLE_ID", columnDefinition = "int8 DEFAULT nextval(\'SEQ_ROLE_ID\'::regclass)")
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
    @SequenceGenerator( name = "seq", sequenceName = "SEQ_ROLE_ID", allocationSize=1, initialValue=1, schema="public")
    public Integer getRoleId() {
        return roleId;
    }

Upvotes: 2

Related Questions