还有些小毛病, 就不说了
完事后总算没有 500 了
问题代码段
private long saveTacoInfo(Taco taco) {
taco.setCreatedAt(new Date());
PreparedStatementCreator psc =
new PreparedStatementCreatorFactory(
"insert into Taco (name, createdAt) values (?, ?)",
Types.VARCHAR, Types.TIMESTAMP
).newPreparedStatementCreator(
Arrays.asList(
taco.getName(),
new Timestamp(taco.getCreatedAt().getTime())));
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbc.update(psc, keyHolder);
return keyHolder.getKey().longValue();
}
代码
private long saveTacoInfo(Taco taco) {
taco.setCreateAt(new Date());
/* 这一段, 是 拉美老哥 的代码
PreparedStatementCreator psc =
new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
String sql = "insert into Taco (name, createdAt) values (?, ?)";
PreparedStatement ps = connection.prepareStatement(sql, new String[]{"id"});
ps.setString(1, taco.getName());
ps.setTimestamp(2, new Timestamp(taco.getCreateAt().getTime()));
return ps;
}
};*/
// 这一段是我改的代码
PreparedStatementCreatorFactory pscf = new PreparedStatementCreatorFactory( // 创建语句
"insert into Taco (name, createdAt) values (?, ?)",
Types.VARCHAR, Types.TIMESTAMP
);
// 关键方法
pscf.setReturnGeneratedKeys(true);
PreparedStatementCreator psc = pscf.newPreparedStatementCreator( // 传参
Arrays.asList(
taco.getName(),
new Timestamp(taco.getCreateAt().getTime())
)
);
KeyHolder keyHolder = new GeneratedKeyHolder();
jdbc.update(psc, keyHolder);
return keyHolder.getKey().longValue(); // 获得结果
}
Spring - jdbcTemplate - 调试代码: PreparedStatementCreator 生成的语句, update 之后没有 自增id, 已解决
原文:https://www.cnblogs.com/xy14/p/11761969.html