Id generation issue with Hibernate, liquibase and

2019-05-18 05:22发布

I've created a table using liquibase:

<createTable tableName="employees">
    <column name="id" type="bigint">
        <constraints primaryKey="true" nullable="false"/>
    </column>
    <column name="name" type="varchar(50)">
        <constraints nullable="false"/>
    </column>
</createTable>

The following sql ddl query is generated:

CREATE TABLE employees (id BIGINT NOT NULL, name VARCHAR(50) NOT NULL, CONSTRAINT PK_EMPLOYEES PRIMARY KEY (id));

The corresponding entity:

@Entity
@Table(name="employees")
public class EmployeeAccessProperty ...
    @Id
    @GeneratedValue
    public long getId() {
        return id;
    }
...

Now, when I try to save it via JPA implementation, the sql query is generated to insert data:

Hibernate: insert into employees (id, name) values (default, ?)
2013-05-20T14:29:22.525+0700  WARN  SQL Error: -5544, SQLState: 42544
2013-05-20T14:29:22.526+0700  ERROR  DEFAULT keyword cannot be used as column has no DEFAULT

I expected, that when I don't specify id generation strategy, Hibernate will choose the best one according to the provider. I don't understand why for ID generation the default value is tried to be used. I'm not sure, which side is responsible for the error: hibernate, liqubase or hsqldb.

What can I do to resolve the problem? Please help me.

2条回答
Anthone
2楼-- · 2019-05-18 05:53

You are not telling to your database that your primary key must be autogenerated. Create your table this way :

CREATE TABLE employees (id BIGINT GENERATED BY DEFAULT AS IDENTITY, name VARCHAR(50) NOT NULL, CONSTRAINT PK_EMPLOYEES PRIMARY KEY (id));
查看更多
我命由我不由天
3楼-- · 2019-05-18 05:57

Hibernate indeed chooses the most appropriate strategy depending on the dialect. Since HSQLDB supports identity columns, it uses this strategy. This strategy supposes that the ID column is autogenerated by the database, and you didn't define it as such, so it doesn't work.

Define the column as generated by default as identity, and everything should be fine. Or choose another generation strategy using a sequence or a table (that you'll aslo have to define in the database).

查看更多
登录 后发表回答