Created
September 10, 2011 14:34
-
-
Save amolbrid/1208369 to your computer and use it in GitHub Desktop.
Spring: How to get auto generated keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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