JdbcTemplate如何自动生成主键

时间:2014-05-22 11:01:20

标签: java sql spring hsqldb jdbctemplate

我正在使用spring,它是用于数据库连接的JdbcTemplate,我正在尝试为我的主键列自动生成一个键。我也在使用HSQLDB。该表看起来像:

CREATE TABLE IF NOT EXISTS Customers (
    cid BIGINT GENERATED BY DEFAULT AS PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    ...
);

我的Dao对象中的代码如下所示:

Map<String, Object> values = new HashMap<String, Object>();
values.put("name", customer.getName()); 
// NOT putting the cid
...
SimpleJdbcInsert insert = new SimpleJdbcInsert(jdbc).withTableName(
                "CUSTOMERS").usingGeneratedKeyColumns("CID");
Long key = (Long) insert.executeAndReturnKey(values);

正如您所看到的,我没有手动输入密钥,我希望usingGeneratedKeyColumns方法会自动为我生成密钥。无论如何,我在执行executeAndReturnKey后出现此错误:

org.springframework.dao.DataIntegrityViolationException: PreparedStatementCallback; SQL []; integrity constraint violation: NOT NULL check constraint; SYS_PK_10094 table: CUSTOMERS column: CID; nested exception is java.sql.SQLIntegrityConstraintViolationException: integrity constraint violation: NOT NULL check constraint; SYS_PK_10094 table: CUSTOMERS column: CID

1 个答案:

答案 0 :(得分:1)

问题是HSQLDB自动生成密钥的语法略有不同。您需要将其定义为IDENTITY,然后定义为PRIMARY KEY

CREATE TABLE IF NOT EXISTS Customers (
    cid BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    ...
);