以前使用JdbcTemplate来获取自增列的值,现在发现NamedParameterJdbcTemplate也可以,而且后者大部分情况下,其实更加方便。
我们来看下二者的具体例子:
@Component public class NamedJdbcServiceImpl implements NamedJdbcService { @Autowired NamedParameterJdbcTemplate njdbcTp; @Autowired JdbcTemplate jdbcTp; @Override @Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.DEFAULT,rollbackFor=Exception.class) public int addFamilyWithNJT(String name) { String sql="insert into family(name) values(:name)"; //使用map传递参数 Map<String,Object> args=new HashMap<String,Object>(); args.put("name",name); KeyHolder keyHolder=new GeneratedKeyHolder(); SqlParameterSource paramSource=new MapSqlParameterSource(args); int qty=njdbcTp.update(sql, paramSource, keyHolder); return keyHolder.getKey().intValue(); } @Override @Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.DEFAULT,rollbackFor=Exception.class) public int addFamilyWithNJT2(String name) { String sql="insert into family(name) values(:name)"; //使用bean/pojo传递参数 Family family=new Family(name); KeyHolder keyHolder=new GeneratedKeyHolder(); SqlParameterSource paramSource=new BeanPropertySqlParameterSource(family); int qty=njdbcTp.update(sql, paramSource, keyHolder); return keyHolder.getKey().intValue(); } @Override @Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.DEFAULT,rollbackFor=Exception.class) public int addFamilyWithJT(String name) { KeyHolder keyHolder=new GeneratedKeyHolder(); jdbcTp.update(new PreparedStatementCreator() { @Override public PreparedStatement createPreparedStatement(Connection con) throws SQLException { String sql="insert into family(name) values(?)"; PreparedStatement ps = null; ps = con.prepareStatement(sql, new String[] { "custom_id"}); ps.setInt(1, Integer.valueOf(name)); return ps; }},keyHolder); return keyHolder.getKey().intValue(); } }
SqlParameterSource 接口有多个实现,具体如下图:
具体的后代有 BeanPropertySqlParameterSource和MapSqlParameterSource。
这两个实现类的作用就和它们的名字一样,分别通过bean和map的传递值,关联的方式分别是属性和key的名称必须和命名参数的名称一致即可。