I have an auto generated timestamp that is created each time a record is inserted or updated in a mysql table. Is there a way to return this timestamp in a way similar to how I would use a keyholder to return a newly created id?
KeyHolder keyHolder = new GeneratedKeyHolder();
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
//Insert Contact
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement preparedStatement = connection.prepareStatement(SQL_ADD, Statement.RETURN_GENERATED_KEYS);
preparedStatement.setString(1, contact.getFirstName());
preparedStatement.setString(2, contact.getLastName());
preparedStatement.setInt(3, contact.getOrganizationId());
preparedStatement.setString(4, contact.getType());
preparedStatement.setInt(5, contact.getUserId());
return preparedStatement;
}
}, keyHolder);
//Use keyholder to obtain newly created id
contact.setId(keyHolder.getKey().intValue());
Is there some way to also return the new timestamp without having to requery the table? I have been looking for ways to return it along with the id as a key in the keyholder, but it doesn’t seem to be returned as a key?
There are few options for solving this issue on the MySQL database server side. You could start with creating a
TRIGGERon the table. AsTRIGGERhas a restriction and cannot return data, you can set theTIMESTAMPvalue to a variable:To retrieve this timestamp value, run the following command:
Since the variables are stored in the memory, there will be no need to open any tables again.
You go even further. You could create a
STORED PROCEDUREin MySQL to automate all the above (sample code, as I do not know your table’s details):You can run this procedure with the following code:
As I’m not familiar with the Java, you’ll need to finish it up with your side of code.