日期:2014-05-20  浏览次数:21027 次

h2 database无法获得最后的字段子增值
项目中使用了h2 database内存数据库,用LAST_INSERT_ID()在它本身的WEB界面里面能够获取最后的自增值,但是在项目里面就获取不到,返回的类型为null,跟整合mybatis了
sql配置为:
<select id="selectId" resultType="java.lang.Long">
<![CDATA[
SELECT LAST_INSERT_ID() as id
]]>
</select>

------解决方案--------------------
试一试 Statement getGeneratedKeys()
Java code
String sql = "INSERT INTO tbl (col) VALUES (?)";
preparedStatement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, col);
preparedStatement.executeUpdate();
generatedKeys = preparedStatement.getGeneratedKeys();
if (generatedKeys.next()) {
    long id = generatedKeys.getLong(1);
} else {
    // Throw exception?
}