Id generation issue with Hibernate, liquibase and hsqldb

霸气de小男生 提交于 2019-12-07 14:41:14

问题


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.


回答1:


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



回答2:


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).



来源:https://stackoverflow.com/questions/16644765/id-generation-issue-with-hibernate-liquibase-and-hsqldb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!