Skip to content

Instantly share code, notes, and snippets.

@amolbrid
Created September 10, 2011 14:34
Show Gist options
  • Save amolbrid/1208369 to your computer and use it in GitHub Desktop.
Save amolbrid/1208369 to your computer and use it in GitHub Desktop.
Spring: How to get auto generated keys
public class UserDao extends SimpleJdbcDaoSupport {
private static final String CREATE_USER_SQL = "insert into users(name, created_at, updated_at) values (?,?,?)";
public int createUser(String username) {
Connection cnn = null;
PreparedStatement pstmt = null;
ResultSet rsId = null;
int id = 0;
try {
cnn = DataSourceUtils.doGetConnection(getDataSource());
pstmt = cnn.prepareStatement(CREATE_USER_SQL, Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, username);
Timestamp ts = new Timestamp(System.currentTimeMillis());
pstmt.setTimestamp(2, ts);
pstmt.setTimestamp(3, ts);
pstmt.executeUpdate();
rsId = pstmt.getGeneratedKeys();
if(rsId.next()) {
id = rsId.getInt(1);
}
} catch (CannotGetJdbcConnectionException e) {
logger.error(e.getMessage(), e);
} catch (SQLException e) {
logger.error(e.getMessage(), e);
} finally {
if(rsId != null) {
try { rsId.close(); } catch(SQLException e) {}
}
if(pstmt != null) {
try { pstmt.close(); } catch(SQLException e) {}
}
if(cnn != null) {
try {
DataSourceUtils.doReleaseConnection(cnn, getDataSource());
} catch(SQLException e) {}
}
}
return id;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment