【SSM开发框架】Spring之事务控制

笔记输出来源:拉勾教育Java就业急训营
如有侵权,私信立删

修改时间:2020年2月23日
作者:pp_x
邮箱:[email protected]

JdbcTemplate

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

核心对象

JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSource dataSource);

核心方法

  • int update():执行增、删、改语句
  • List<T> query():查询多条结果
  • T queryForObject():查询一条结果
  • new BeanPropertyRowMapper<>():实现ORM封装

Spring整合JdbcTemplate

代码实现

  • 坐标
 <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.15</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.13</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
<!--     事务jar包   -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
    </dependencies>
  • 配置文件
<!--  IOC扫描注解  -->
    <context:component-scan base-package="com.lagou"/>
<!--  引入properties  -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
<!--  数据源datasource  -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
<!--  JDBCTemplate  -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg name="dataSource" ref="dataSource"/>
    </bean>
  • dao的实现类
@Repository
public class AccountImpl implements AccountDao {
    
    

    @Autowired
    private JdbcTemplate jdbcTemplate;
    public List<Account> findAll() {
    
    
        //需要用到jdbcTemplate
        String sql = "select * from account";
        List<Account> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<Account>(Account.class));
        return list;
    }

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

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

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

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

Spring的事务控制

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

编程式事务控制相关对象

PlatformTransactionManager

  • PlatformTransactionManager接口,是spring的事务管理器。
方法 说明
TransactionStatus getTransaction(TransactionDefinition definition) 获取事务的状态信息
void commit(TransactionStatus status); 提交事务
void rollback(TransactionStatus status) 回滚事务
  • PlatformTransactionManager 是接口类型,不同的 Dao 层技术则有不同的实现类。
    • DataSourceTransactionManager :dao层技术是jdbcTemplate和mybatis时
    • HibernateTransactionManager:dao层技术是是hibernate时
    • JpaTransactionManager:dao层技术是JPA时

TransactionDefinition

  • TransactionDefinition接口提供事务的定义信息(事务隔离级别、事务传播行为等等)
  • 定义了事务的一些相关参数
方法 说明
int getIsolationLevel() 获得事务的隔离级别
int getPropogationBehavior() 获得事务的传播行为
int getTimeout() 获得超时时间
boolean isReadOnly() 是否只读

事务隔离级别

  • 设置隔离级别,可以解决事务并发产生的问题,如脏读、不可重复读和虚读(幻读)
    • ISOLATION_DEFAULT :使用数据库默认级别
    • ISOLATION_READ_UNCOMMITTED:读未提交
    • ISOLATION_READ_COMMITTED:读已提交
    • ISOLATION_REPEATABLE_READ:可重复读
    • ISOLATION_SERIALIZABLE:串行化
  • 事务相关知识链接

事务传播行为

  • 事务传播行为指的就是当一个业务方法【被】另一个业务方法调用时,应该如何进行事务控制。
    • REQUIRED:如果当前没有事务,就新建一个事务,如果已经存在一个事务中,加入到这个事务中
    • SUPPORTS:支持当前事务,如果当前没有事务,就以非事务方式执行(没有事务)
    • MANDATORY:使用当前的事务,如果当前没有事务,就抛出异常
    • REQUERS_NEW:新建事务,如果当前在事务中,把当前事务挂起
    • NOT_SUPPORTED:以非事务方式执行操作,如果当前存在事务,就把当前事务挂起
    • NEVER:以非事务方式运行,如果当前存在事务,抛出异常
    • NESTED:如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则执行REQUIRED 类似的操作
      在这里插入图片描述
  • read-only(是否只读):建议查询时设置为只读
  • timeout(超时时间):默认值是-1,没有超时限制。如果有,以秒为单位进行设置

TransactionStatus

  • TransactionStatus 接口提供的是事务具体的运行状态
方法 说明
boolean isNewTransaction() 是否是新事务
boolean hasSavepoint() 是否是回滚点
boolean isRollbackOnly() 事务是否回滚
boolean isCompleted() 事务是否完成

代码实现

  • 配置文件
<!--事务管理器交给IOC--> 
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
	<property name="dataSource" ref="dataSource"/> 
</bean>
  • 业务层代码
@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); 
		} 
	} 
}

总结

  • 事务管理器通过读取事务定义参数进行事务管理,然后会产生一系列的事务状态

基于XML的声明式事务控制

  • 在 Spring 配置文件中声明式的处理事务来代替代码式的处理事务底层采用AOP思想来实现的
  • 声明式事务控制明确事项:
    • 核心业务代码(目标对象)
    • 事务增强代码(Spring已提供事务管理器)
    • 切面配置
  • 使用<tx:advice>标签配置通知增强
    • transaction-manager :指定事务管理器对象
    • name:切点方法
    • isolation:隔离级别
    • propagation:传播行为
    • read-only:是否只读
    • timeout:超时时间
  • 配置aop使用<aop:advisor>

代码实现

  • 事务管理器通知配置
  <!--事务管理器交给IOC-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
<!-- 通知增强   -->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <!-- 定义事务的一些属性    *表示当前一切的方法都走默认配置   -->
        <!--
        name:切点方法
        isolation:隔离级别
        propagation:传播行为
        read-only:是否只读
        timeout:超时时间
              -->
        <tx:attributes>
            <tx:method name="*" isolation="REPEATABLE_READ" propagation="REQUIRED" read-only="false" timeout="-1"/>
        <!--  CRUD基本配置       以save开头 以delete开头   -->
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
<!-- aop配置   -->
    <aop:config>
        <!-- 声明式配置使用advisor       -->
        <aop:advisor advice-ref="txAdvice" pointcut = "execution(* com.lagou.service.impl.AccountServiceImpl.*(..))"/>
    </aop:config>
  • CRUD常用配置
 <!--  CRUD基本配置       以save开头 以delete开头   -->
        <tx:method name="save*" propagation="REQUIRED"/>
        <tx:method name="delete*" propagation="REQUIRED"/>
        <tx:method name="update*" propagation="REQUIRED"/>
        <tx:method name="find*" read-only="true"/>
        <tx:method name="*"/>

基于注解的声明式事务控制

  • @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, timeout = -1, readOnly = false)
  • <tx:annotation-driven/>:事务注解支持xml标签
  • @EnableTransactionManagement:事务注解支持注解等同于<tx:annotation-driven/>

代码实现

  • 业务层
@Service
public class AccountServiceImpl implements AccountService {
    
    
    @Autowired
    private AccountDao accountDao;
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, timeout = -1, readOnly = false)
    public void transfer(String outUser, String inUser, Double money) {
    
    
        //调用dao的out及in方法
        accountDao.out(outUser,money);
        int i  = 2/0;
        accountDao.in(inUser,money);

    }
}
  • 数据源配置类
@PropertySource("classpath: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("dataSource")//把当前方法的返回值对象放进ioc容器中  spring加载核心配置类时自动调用该方法
    public DataSource getDataSource(){
    
    
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        return druidDataSource;
    }
}
  • 核心配置类
@Configuration//声明为核心配置类
@ComponentScan("com.lagou")//包扫描
@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;
    }
}

Spring继承Web环境

ApplicationContext应用上下文获取方式

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

Spring提供获取上下文对象的工具

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

代码实现

  • 需要的坐标
<dependency> 
	<groupId>org.springframework</groupId> 
	<artifactId>spring-context</artifactId> 
	<version>5.1.5.RELEASE</version> 
</dependency> 
<dependency> 
	<groupId>org.springframework</groupId> 
	<artifactId>spring-web</artifactId> 
	<version>5.1.5.RELEASE</version> 
</dependency>
  • web.xml中配置ContextLoaderListener监听器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
<!--  全局参数  指定applicationContext.xml文件的路径  -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

<!--  Spring监听器 contextLoaderListener  -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>
  • 通过工具获得应用上下文对象
 ApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
        Account account = (Account) webApplicationContext.getBean("account");

猜你喜欢

转载自blog.csdn.net/weixin_46303867/article/details/113997539