5

I'm programming with plain JDBC a DAO layer because I only have 61.38 MB on Java Memory in my Tomcat (service hosting). I have a table with an AUTO_INCREMENT column in MySQL. The current implementation has no problems. But I would like to know the value that was generated in the AUTO_INCREMENT column.

The current code looks as follows in the method that inserts a new row.

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 {
        ...
    }
}

I have seen that this is possible in Hibernate, but because I have little memory, is not a feasible option.

I appreciate the help.

Paul Vargas
  • 40,346
  • 15
  • 98
  • 144

1 Answers1

6

There are two ways:

Muad'Dib
  • 432
  • 4
  • 10
Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175