【问题标题】:JdbcTemplate how to auto generate primary keyJdbcTemplate 如何自动生成主键
【发布时间】:2014-05-22 11:01:20
【问题描述】:

我正在使用 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

【问题讨论】:

  • 你为什么要这样做?只需让您的数据库使用自动增量生成密钥。

标签: java sql spring hsqldb jdbctemplate


【解决方案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,
    ...
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    • 2017-10-10
    • 2016-09-24
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多