2014-05-22 60 views
1

我使用的弹簧,它的JdbcTemplate的数据库连接,我试图自动为我的主键列的关键。我也在使用HSQLDB。该表看起来像这样:的JdbcTemplate如何自动生成主键

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

+0

为什么要这么做?让你的数据库使用自动增量生成密钥。 – Stultuske

回答

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