为什么“ Spring in Action 5”中的代码不起作用(keyHolder.getKey()返回null,但是实体保存在DB中)?
private long savePizzaInfo(Pizza pizza) {
pizza.setCreatedAt(new Date());
PreparedStatementCreator psc =
new PreparedStatementCreatorFactory(
"insert into PIZZA (name, createdAt) values (?, ?)",
Types.VARCHAR, Types.TIMESTAMP
).newPreparedStatementCreator(
Arrays.asList(
pizza.getName(),
new Timestamp(pizza.getCreatedAt().getTime())));
KeyHolder keyHolder = new GeneratedKeyHolder();
template.update(psc, keyHolder);
return keyHolder.getKey().longValue();
}
我的数据库表:
CREATE TABLE PIZZA
(
ID bigint DEFAULT (NEXT VALUE FOR
PUBLIC.SYSTEM_SEQUENCE_12CA966F_4FFD_469C_BA69_80BB93916EF3) AUTO_INCREMENT
PRIMARY KEY NOT NULL,
NAME varchar(50) NOT NULL,
CREATEDAT timestamp NOT NULL
);
CREATE UNIQUE INDEX PRIMARY_KEY_4 ON PIZZA (ID);
答案 0 :(得分:5)
您必须指示PreparedStatementCreatorFactory
实例返回生成的密钥:
PreparedStatementCreatorFactory preparedStatementCreatorFactory = new PreparedStatementCreatorFactory(
"insert into PIZZA (name, createdAt) values (?, ?)",
Types.VARCHAR, Types.TIMESTAMP
);
// By default, returnGeneratedKeys = false so change it to true
preparedStatementCreatorFactory.setReturnGeneratedKeys(true);
PreparedStatementCreator psc =
preparedStatementCreatorFactory.newPreparedStatementCreator(
Arrays.asList(
pizza.getName(),
new Timestamp(pizza.getCreatedAt().getTime())));
答案 1 :(得分:0)
您需要指定准备好的陈述 注意下面的代码中的Statement.RETURN_GENERATED_KEYS 您需要像这样的
final PreparedStatementCreator psc = new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(final Connection connection) throws SQLException {
final PreparedStatement ps = connection.prepareStatement("INSERT INTO `names` (`name`) VALUES (?)",
Statement.RETURN_GENERATED_KEYS);
ps.setString(1, name);
return ps;
}
};
答案 2 :(得分:0)
为什么不改用SimpleJdbcInsert?
dbcInsert = new SimpleJdbcInsert(jdbcTemplate);
jdbcInsert.withTableName("TABLE_NAME").usingGeneratedKeyColumns(
"Primary_key");
Map<String, Object> parameters = new HashMap<>();
parameters.put("Column_NAME1", bean.getval1());
parameters.put("Column_NAME2", bean.getval2());
// execute insert
Number key = jdbcInsert.executeAndReturnKey(new MapSqlParameterSource(
parameters));
// convert Number to Int using ((Number) key).intValue()
return ((Number) key).intValue();