[英]Spring 3.2 retrieving auto-generated keys using SimpleJdbcInsert
As per Spring 3.2 Data access docs , SimpleJdbcInsert can be use to retrieve auto generated keys. 根据Spring 3.2数据访问文档 ,SimpleJdbcInsert可用于检索自动生成的密钥。 But, I cannot override the final method setDataSource from JdbcDaoSupport in the code below:
但是,我无法在以下代码中从JdbcDaoSupport覆盖最终方法setDataSource:
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. Spring 3.2文档中未扩展JdbcDaoSupport类。 So, I have 2 questions:
所以,我有两个问题:
How to use SimpleJdbcInsert to retrieve auto-generated keys while extending JdbcDaoSupport class? 扩展JdbcDaoSupport类时如何使用SimpleJdbcInsert检索自动生成的密钥?
If I do not extend JdbcDaoSupport then what shall be the code changes in the configuration file and dao class. 如果我不扩展JdbcDaoSupport,那么配置文件和dao类中的代码将发生什么变化。 Please find below current configuration and dao code:
请在下面找到当前配置和dao代码:
configuration file: 配置文件:
<bean id="loginDao" class="com.vikas.dao.LoginDAO"
p:dataSource-ref="dataSource" />
relevant doa code: 相关的Doa代码:
getJdbcTemplate().update(...);
You can use a variation of SimpleJDBCInsert
which takes JdbcTemplate
as the constructor argument. 您可以使用
SimpleJDBCInsert
的变体,该变体将JdbcTemplate
作为构造函数参数。
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: 删除JdbcDaoSupport之后,可以通过以下更改使用SimpleJdbcInsert检索自动生成的密钥:
configuration file: 配置文件:
<bean id="loginDao" class="com.vikas.dao.LoginDAOImpl"
p:dataSource-ref="dataSource" />
DAO class: DAO类:
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. 我仍在寻找扩展JdbcDaoSupport时使用SimpleJdbcInsert的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.