使用JDBC PreparedStatement在MySql中返回生成的键

时间:2012-05-07 20:54:05

标签: java jdbc dao

我使用普通JDBCDAO图层进行编程,因为我的 Tomcat中的 Java内存上只有 61.38 MB (服务托管)。我在MySQL中有一个包含AUTO_INCREMENT列的表。目前的实施没有问题。但我想知道AUTO_INCREMENT列中生成的值。

当前代码在插入新行的方法中如下所示。

public Integer store(MyBean bean) throws DAOException {
    Connection conn = null;
    PreparedStatement ps = null;
    try {
        conn = getConnection();
        ps = conn.prepareStatement("INSERT ...");
        if (bean.getSomeProperty() != null) {
            ps.setShort(1, bean.getSomeProperty());
        } else {
            ps.setNull(1, Types.SMALLINT);
        }

        /* Other fields */

        int rows = ps.executeUpdate();
        if (rows == 1) {
            // RETURN the generated value
        }
        return null;
    } catch (SQLException e) {
        throw new DAOException(e);
    } finally {
        ...
    }
}

我已经看到这可以在 Hibernate 中使用,但因为我的内存很少,所以不是一个可行的选择。

我很感激帮助。