栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

三、Spring JDBCTemplate & 声明式事务

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

三、Spring JDBCTemplate & 声明式事务

一、Spring JDBCTemplate 1.JDBCTemplate是什么?

JdbcTemplate是spring框架中提供的一个模板对象,对原始繁琐的Jdbc API对象的简单封装。
核心对象

JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSource dataSource);

核心方法

int update(); 执行增、删、改语句
List query(); 查询多个
T queryForObject(); 查询一个
	new BeanPropertyRowMapper<>(); 实现ORM映射封装

举个栗子

public class JdbcTemplateTest {
	@Test
	public void testFindAll() throws Exception {
	// 创建核心对象
	JdbcTemplate jdbcTemplate = new JdbcTemplate(JdbcUtils.getDataSource());
	// 编写sql
	String sql = "select * from account";
	// 执行sql
	List list = jdbcTemplate.query(sql, new BeanPropertyRowMapper
	(Account.class));
	}
}

account表

CREATE TABLE `account` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) DEFAULT NULL,
  `money` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8

jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_db
jdbc.username=root
jdbc.password=root

2.Spring整合JDBCTemplate

需求: 基于Spring的xml配置实现账户的CRUD操作

①:导入依赖坐标
	
        
            mysql
            mysql-connector-java
            5.1.47
        
        
            com.alibaba
            druid
            1.1.15
        
        
            org.springframework
            spring-context
            5.1.5.RELEASE
        
        
            org.aspectj
            aspectjweaver
            1.8.13
        
        
            org.springframework
            spring-jdbc
            5.1.5.RELEASE
        
        
            org.springframework
            spring-tx
            5.1.5.RELEASE
        
        
            junit
            junit
            4.12
        
        
            org.springframework
            spring-test
            5.1.5.RELEASE
        
    
②:编写Account实体类
public class Account {

    private Integer id;
    private String name;
    private Double money;
}
③:编写AccountDao接口和实现类
public interface AccountDao {
    
    List findAll();

    
    Account findById(Integer id);

    
    void save(Account account);

    
    void update(Account account);

    
    void delete(Integer id);
}
@Repository
public class AccountDaoImpl implements AccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplatel;

    public List findAll() {
        String sql = "select * from account";
        List list = jdbcTemplatel.query(sql, new BeanPropertyRowMapper(Account.class));
        return list;
    }

    public Account findById(Integer id) {
        String sql = "select * from account where id = ?";
        Account account = jdbcTemplatel.queryForObject(sql, new BeanPropertyRowMapper(Account.class), id);
        return account;
    }

    public void save(Account account) {
        String sql = "insert into account values(null,?,?)";
        jdbcTemplatel.update(sql,account.getName(),account.getMoney());
    }

    public void update(Account account) {
        String sql = "update account set money = ? where name = ?";
        jdbcTemplatel.update(sql,account.getMoney(),account.getName());
    }

    public void delete(Integer id) {
        String sql = "delete from account where id = ?";
        jdbcTemplatel.update(sql,id);
    }
}

④:编写AccountService接口和实现类
public interface AccountService {
    
    List findAll();

    
    Account findById(Integer id);

    
    void save(Account account);

    
    void update(Account account);

    
    void delete(Integer id);
}
@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;

    public List findAll() {
        return accountDao.findAll();
    }

    public Account findById(Integer id) {
        return accountDao.findById(id);
    }

    public void save(Account account) {
        accountDao.save(account);
    }

    public void update(Account account) {
        accountDao.update(account);
    }

    public void delete(Integer id) {
        accountDao.delete(id);
    }
}
⑤:编写Spring核心配置文件


    
    

    

    
        
        
        
        
    
    
        
    


⑥:测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext.xml"})
public class TestSpringJdbcTemplate {
    @Autowired
    private AccountService accountService;

    // 测试保存
    @Test
    public void testSave() {
        Account account = new Account();
        account.setName("马双");
        account.setMoney(1000d);
        accountService.save(account);
    }

    // 测试查询所有
    @Test
    public void testFindAll() {
        List list = accountService.findAll();
        for (Account account : list) {
            System.out.println(account);
        }
    }

    // 测试根据id查询账户
    @Test
    public void testFindById() {
        Account account = accountService.findById(1);
        System.out.println(account);
    }

    // 测试修改账户信息
    @Test
    public void testUpdate() {
        Account account = new Account();
        account.setMoney(1000d);
        account.setName("徐国文");
        accountService.update(account);
    }
    // 测试根据id删除账户信息
    @Test
    public void testDelete() {
        accountService.delete(5);
    }
}


3.Spring整合JDBCTemplate 实现转账案例 ①:导入依赖坐标

        
            mysql
            mysql-connector-java
            5.1.47
        
        
            com.alibaba
            druid
            1.1.15
        
        
            org.springframework
            spring-context
            5.1.5.RELEASE
        
        
            org.aspectj
            aspectjweaver
            1.8.13
        
        
            org.springframework
            spring-jdbc
            5.1.5.RELEASE
        
        
            org.springframework
            spring-tx
            5.1.5.RELEASE
        
        
            junit
            junit
            4.12
        
        
            org.springframework
            spring-test
            5.1.5.RELEASE
        
    
②:编写Account实体类 ③:编写AccountDao接口和实现类
public interface AccountDao {
    
    void out(String outUser,Double money);

    
    void in(String inUser,Double money);
}
@Repository
public class AccountDaoImpl implements AccountDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    public void out(String outUser, Double money) {
        String sql = "update account set money = money - ? where name = ?";
        jdbcTemplate.update(sql,money,outUser);
    }

    
    public void in(String inUser, Double money) {
        String sql = "update account set money = money + ? where name = ?";
        jdbcTemplate.update(sql,money,inUser);
    }
}

④:编写AccountService接口和实现类
public interface AccountService {
    
    void transfer(String outUser,String inUser,Double money);
}

@Service
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;

    public void transfer(String outUser, String inUser, Double money) {

        // 转出操作
        accountDao.out(outUser,money);

        // int i = 1 / 0;

        // 转入操作
        accountDao.in(inUser,money);
    }
}
⑤:编写Spring核心配置文件



    
    

    
    

    
        
        
        
        
    

    
        
    


⑥:测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext.xml"})
public class SpringJdbcTemplateTx {
    @Autowired
    private AccountService accountService;

    @Test
    public void testTransfer() {
        accountService.transfer("tom","jerry",100d);
    }
}

二、Spring的事务 1.Spring中的事务控制方式

Spring的事务控制可以分为编程式事务控制和声明式事务控制。
编程式: 开发者直接把事务的代码和业务代码耦合到一起,在实际开发中不用。
声明式: 开发者采用配置的方式来实现的事务控制,业务代码与事务代码实现解耦合,使用的AOP思想。


2.编程式事务控制相关对象【了解】 ①:PlatformTransactionManager

PlatformTransactionManager接口,是spring的事务管理器,里面提供了我们常用的操作事务的方法。

方法说明
TransactionStatus getTransaction(TransactionDefinition definition)获取事务的状态信息
void commit(TransactionStatus status)提交事务
void rollback(TransactionStatus status)回滚事务

注意

* PlatformTransactionManager 是接口类型,不同的 Dao 层技术则有不同的实现类。
   * Dao层技术是jdbcTemplate或mybatis时:
   		DataSourceTransactionManager
   * Dao层技术是hibernate时:
   		HibernateTransactionManager
   * Dao层技术是JPA时:
   		JpaTransactionManager

②: TransactionDefinition

TransactionDefinition接口提供事务的定义信息(事务隔离级别、事务传播行为等等)

方法说明
int getIsolationLevel()获得事务的隔离级别
int getPropogationBehavior()获得事务的传播行为
int getTimeout()获得超时时间
boolean isReadonly()是否只读

a): 事务隔离级别

设置隔离级别,可以解决事务并发产生的问题,如脏读、不可重复读、幻读(虚读)。

* ISOLATION_DEFAULT 使用数据库默认级别
* ISOLATION_READ_UNCOMMITTED 读未提交
* ISOLATION_READ_COMMITTED 读已提交
* ISOLATION_REPEATABLE_READ 可重复读
* ISOLATION_SERIALIZABLE 串行化

b): 事务传播行为

事务传播行为指的就是当一个业务方法【被】另一个业务方法调用时,应该如何进行事务控制。

参数说明
REQUIRED如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中。一般的选择(默认值)
SUPPORTS支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
MANDATORY使用当前的事务,如果当前没有事务,就抛出异常
REQUERS_NEW新建事务,如果当前在事务中,把当前事务挂起
NOT_SUPPORTED以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
NEVER以非事务方式运行,如果当前存在事务,抛出异常
NESTED如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行 REQUIRED 类似的操作


c): read-only(是否只读):建议查询时设置为只读 d): timeout(超时时间):默认值是-1,没有超时限制。如果有,以秒为单位进行设置
③: TransactionStatus

TransactionStatus 接口提供的是事务具体的运行状态。

方法说明
boolean isNewTransaction()是否是新事务
boolean hasSavepoint()是否是回滚点
boolean isRollbackonly()事务是否回滚
boolean isCompleted()事务是否完成

可以简单的理解三者的关系:事务管理器通过读取事务定义参数进行事务管理,然后会产生一系列的事务状态。


④:代码实现 a):配置文件

  

b):业务层代码
@Service
public class AccountServiceImpl implements AccountService {
  @Autowired
  private AccountDao accountDao;
  @Autowired
  private PlatformTransactionManager transactionManager;
  @Override
  public void transfer(String outUser, String inUser, Double money) {
  	// 创建事务定义对象
  	DefaultTransactionDefinition def = new DefaultTransactionDefinition();
  	// 设置是否只读,false支持事务
  	def.setReadOnly(false);
  	// 设置事务隔离级别,可重复读mysql默认级别
  	def.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
  	// 设置事务传播行为,必须有事务
  	def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
  	// 配置事务管理器
  	TransactionStatus status = transactionManager.getTransaction(def);
  	try {
  	// 转账
  	accountDao.out(outUser, money);
  	accountDao.in(inUser, money);
  	// 提交事务
  	transactionManager.commit(status);
  	} catch (Exception e) {
  	e.printStackTrace();
  	// 回滚事务
  	transactionManager.rollback(status);
  	}
  }
}

3.基于XML的声明式事务【重点】

在 Spring 配置文件中声明式的处理事务来代替代码式的处理事务。底层采用AOP思想来实现的。
声明式事务控制明确事项:

	- 核心业务代码(目标对象)(切入点是谁?)
	- 事务增强代码(Spring已提供事务管理器)(通知)
	- 切面配置(切面如何配置)
①:快速入门

需求: 使用spring声明式事务控制转账业务。

a):引入tx命名空间


 
b): 事务管理器通知配置
  
        
        
        
        
 


	



	
	
		
		
	

c): 事务管理器AOP切面配置
	
        
    
d):测试事务控制转账业务代码
public void transfer(String outUser, String inUser, Double money{
        // 转出操作
        accountDao.out(outUser,money);

        int i = 1 / 0;

        // 转入操作
        accountDao.in(inUser,money);
}
②:事务参数的配置详解

* name:切点方法名称
* isolation:事务的隔离级别
* propogation:事务的传播行为
* timeout:超时时间
* read-only:是否只读

CRUD常用配置
	根据事务的传播行为进行事务管理器属性的配置,CRUD常用配置
                   这样一来:就需要我们的方法名称规范了起来,
                    如果是增删改 saveXxx() updateXxx() deleteXxx(),
                    如果是查询 findXxx()
                    如果不是增删改查的方法,就一切都走默认配置

	
	
	
	
	


4.基于注解的声明式事务【重点】 ①:修改service层,增加事务注解

@Service
@Transactional
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountDao accountDao;
    // 使用Spring声明式事务增强
    // 当然也可以使该类中的所有方法都接收事务的控制,那么就在该类上添加这个注解,事务的配置都使用默认配置
    // @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.REPEATABLE_READ,readonly = false,timeout = -1)
    public void transfer(String outUser, String inUser, Double money) {
        // 转出操作
        accountDao.out(outUser,money);

        int i = 1 / 0;

        // 转入操作
        accountDao.in(inUser,money);
    }
}
②:在核心配置文件中,开启事务注解支持


	
	
	
		
	
	
	

5.纯注解 ①:核心配置类
@Configuration // 表示该类是spring的核心配置类
@ComponentScan("cn.xuguowen")   // IOC注解扫描
@import(DataSourceConfig.class) // 引入数据源配置类
@EnableTransactionManagement    // 开启声明式事务注解扫描
public class SpringConfig {

    @Bean
    public JdbcTemplate getJdbcTemplate(@Autowired DataSource dataSource) {
        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
        return jdbcTemplate;
    }

    @Bean
    public PlatformTransactionManager getPlatformTransactionManager(@Autowired DataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource);
        return dataSourceTransactionManager;
    }
}
②:数据源配置类
@PropertySource("classpath:jdbc.properties")    // 加载jdbc.properties配置
public class DataSourceConfig {
    @Value("${jdbc.driverClassName}")
    private String driver;
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;

    @Bean   // 将方法的返回值交给IOC容器管理
    public DataSource getDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        return druidDataSource;
    }
}
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///spring_db
jdbc.username=root
jdbc.password=root

三、Spring集成Web环境 1. ApplicationContext应用上下文获取方式

应用上下文对象是通过 new ClasspathXmlApplicationContext(spring配置文件) 方式获取的,但是每次从容器中获得Bean时都要编写new ClasspathXmlApplicationContext(spring配置文件) 。这样的弊端就是配置文件被加载多次,应用上下文对象创建多次。
解决思路分析:
在Web项目中,可以使用ServletContextListener监听Web应用的启动,我们可以在Web应用启动时,就加载Spring的配置文件,创建应用上下文对象ApplicationContext,在将其存储到ServletContext的域中,这样就可以在任意位置从域中获得应用上下文ApplicationContext对象了。

2. Spring提供获取应用上下文的工具

上面的分析不用手动实现,Spring提供了一个监听器ContextLoaderListener就是对上述功能的封装,该监听器内部加载Spring配置文件,创建应用上下文对象,并存储到ServletContext域中,提供了一个客户端工具 WebApplicationContextUtils供使用者获得应用上下文对象。

所以我们需要做的只有两件事:

	- 1.在web.xml中配置ContextLoaderListener监听器(导入spring-web坐标)
	- 2.使用WebApplicationContextUtils获得应用上下文对象ApplicationContext
3. 实现 ①:导入Spring集成web坐标
	
            org.springframework
            spring-web
            5.1.5.RELEASE
    
②:在web.xml文件中配置ContextLoaderListener监听器
    
    
        
        contextConfigLocation
        classpath:applicationContext.xml
    
    
    
        org.springframework.web.context.ContextLoaderListener
    
③:通过客户端工具类获得应用上下文对象
 		// 使用提供得客户端工具类获取spring得上下文对象
        ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
        Account account = (Account) applicationContext.getBean("account");
        System.out.println(account);
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/332289.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号