Spring学习笔记(四)
今天的主要学习内容是通过aop实现Spring的自动事务配置。但Spring的自动事务配置需要使用JdbcTemplate进行持久层编写来配合使用。所以今日的学习内容主要分为了解JdbcTemplated的使用与掌握Spring自动事务配置
一、JdbdTemplate
**1.概述 **
JdbcTemplate是Spring框架提供的一个对象,是对原始Jdbc API的一层简单封装。
JdbcTemplate对象类存在于spring-jdb-5.0.2.RELEASE.jar中,另外Spring的事务控制存在于spring- tx-5.0.2.RELEASE.jar中
2.使用方法
(1)在持久层中 使用JdbcTemplate对象进行数据的增删改查:
/**
* 查找一个
* @param id
* @return
*/
public Account findById(Integer id) {
List<Account> list = jdbcTemplate.query("select * from account where id = ?",new AccountRowMapper(),id);
return list.isEmpty() ? null : list.get(0) ;
}
/**
* 保存账户
* @param account
*/
public void save(Account account) {
jdbcTemplate.update("update account set money = ? where id = ?",account.getMoney(),account.getId());
}
此处仅以增与查为例。jdbcTemplate的方法里需要提供的参数:sql语句,RowMapper对象,sql语句中的未知参数
其中RowMapper是一个接口,因此我们要自己实现一个AccountRowMapper,作为参数传入findById方法。RowMapper的主要作用是:用于指定数据库表属性与被封装对象属性对应关系,类似于MyBatis中的resultMap
(2)定义一个AccountRowMapper类,并编写mapRow方法
class AccountRowMapper implements RowMapper<Account>{
@Override
public Account mapRow(ResultSet resultSet, int i) throws SQLException {
Account account = new Account();
account.setName(resultSet.getString("name"))