As per Spring 3.2 Data access docs , SimpleJdbcInsert can be use to retrieve auto generated keys. But, I cannot override the final method setDataSource from JdbcDaoSupport in the code below:
public class LoginDAOImpl extends JdbcDaoSupport implements LoginDAO {
// Cannot override the final method from JdbcDaoSupport
public void setDataSource(DataSource dataSource) {
}
JdbcDaoSupport class is not extended in the Spring 3.2 doc. So, I have 2 questions:
How to use SimpleJdbcInsert to retrieve auto-generated keys while extending JdbcDaoSupport class?
If I do not extend JdbcDaoSupport then what shall be the code changes in the configuration file and dao class. Please find below current configuration and dao code:
configuration file:
<bean id="loginDao" class="com.vikas.dao.LoginDAO"
p:dataSource-ref="dataSource" />
relevant doa code:
getJdbcTemplate().update(...);
You can use a variation of SimpleJDBCInsert
which takes JdbcTemplate
as the constructor argument.
SimpleJdbcInsert simpleJdbcInsert = new SimpleJdbcInsert(getJdbcTemplate());
This way there is no need to try and get hold of the datasource directly.
自动生成的密钥是在插入而不是更新时生成的
After removing JdbcDaoSupport, I am able to retrieve auto-generated keys using SimpleJdbcInsert by following changes:
configuration file:
<bean id="loginDao" class="com.vikas.dao.LoginDAOImpl"
p:dataSource-ref="dataSource" />
DAO class:
public class LoginDAOImpl implements LoginDAO {
private JdbcTemplate jdbcTemplate;
private SimpleJdbcInsert insertPerson;
public void setDataSource(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
insertPerson = new SimpleJdbcInsert(dataSource).withTableName("PERSON")
.usingGeneratedKeyColumns("PERSON_ID");
}
@Override
public void addPerson(Person person) {
SqlParameterSource parameters = new BeanPropertySqlParameterSource(
person);
Number newId = insertPerson.executeAndReturnKey(parameters);
String sql = "INSERT INTO PERSON_ROLE (PERSON_ID, ROLE) VALUES (?, ?)";
jdbcTemplate.update(sql, newId.longValue(), person.getPersonRole().getRole());
}
}
I am still looking for a way to use SimpleJdbcInsert while extending JdbcDaoSupport.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.