【发布时间】: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