Spring 基础知识五

无情 阅读:653 2021-03-31 14:14:31 评论:0

第一 Spring 事务控制API介绍

1.1 PlatformTransactionManager:

      此接口是 spring 的事务管理器,它里面提供了我们常用的操作事务的方法,如下图:

1.2 开发中常用的PlatformTransactionManager接口实现类:

1.3 TransactionDefinition

       它是事务对象,里面有如下方法:

1.3.1 事务的隔离级别

1.3.2 事务的传播行为

1.3.3 超时时间

         默认值是-1,没有超时限制。如果有,以秒为单位进行设置。 

1.3.4 是否是只读事务

         建议查询时设置为只读。

1.4 TransactionStatus

      此接口提供的是事务具体的运行状态,方法介绍如下图:

第二  基于 XML 方式进行事务控制

核心代码:

package com.zzg.transaction.entity; 
 
import java.io.Serializable; 
 
@SuppressWarnings("serial") 
public class Account implements Serializable { 
	private Integer id; 
	private String name; 
	private Float money; 
 
	public Integer getId() { 
		return id; 
	} 
 
	public void setId(Integer id) { 
		this.id = id; 
	} 
 
	public String getName() { 
		return name; 
	} 
 
	public void setName(String name) { 
		this.name = name; 
	} 
 
	public Float getMoney() { 
		return money; 
	} 
 
	public void setMoney(Float money) { 
		this.money = money; 
	} 
 
	@Override 
	public String toString() { 
		return "Account [id=" + id + ", name=" + name + ", money=" + money + "]"; 
	} 
 
} 
 
 
package com.zzg.transaction.dao; 
 
import com.zzg.transaction.entity.Account; 
 
public interface IAccountDao { 
	/** 
	* 根据 id 查询账户信息 
	* @param id 
	* @return 
	*/ 
	Account findAccountById(Integer id); 
	/** 
	* 根据名称查询账户信息 
	* @return 
	*/ 
	Account findAccountByName(String name); 
	/** 
	* 更新账户信息 
	* @param account 
	*/ 
	void updateAccount(Account account); 
} 
 
 
package com.zzg.transaction.dao.impl; 
 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.util.List; 
 
import org.springframework.jdbc.core.RowMapper; 
import org.springframework.jdbc.core.support.JdbcDaoSupport; 
 
import com.zzg.transaction.dao.IAccountDao; 
import com.zzg.transaction.entity.Account; 
 
public class AccountDaoImpl extends JdbcDaoSupport implements IAccountDao { 
 
	@Override 
	public Account findAccountById(Integer id) { 
		// TODO Auto-generated method stub 
		List<Account> list = getJdbcTemplate().query("select * from account where id = ? ", new AccountRowMapper(), id); 
		return list.isEmpty() ? null : list.get(0); 
	} 
 
	@Override 
	public Account findAccountByName(String name) { 
		// TODO Auto-generated method stub 
		List<Account> list = getJdbcTemplate().query("select * from account where name = ? ", new AccountRowMapper(), 
				name); 
		if (list.isEmpty()) { 
			return null; 
		} 
		if (list.size() > 1) { 
			throw new RuntimeException("结果集不唯一,不是只有一个账户对象"); 
		} 
		return list.get(0); 
	} 
 
	@Override 
	public void updateAccount(Account account) { 
		getJdbcTemplate().update("update account set money = ? where id = ? ",account.getMoney(),account.getId()); 
	} 
 
	class AccountRowMapper implements RowMapper<Account> { 
 
		@Override 
		public Account mapRow(ResultSet rs, int rowNum) throws SQLException { 
			// TODO Auto-generated method stub 
			Account account = new Account(); 
			account.setId(rs.getInt("id")); 
			account.setName(rs.getString("name")); 
			account.setMoney(rs.getFloat("money")); 
			return account; 
		} 
 
	} 
 
} 
 
 
package com.zzg.transaction.service; 
 
import com.zzg.transaction.entity.Account; 
 
public interface IAccountService { 
	/** 
	* 根据 id 查询账户信息 
	* @param id 
	* @return 
	*/ 
	Account findAccountById(Integer id);//查 
	/** 
	* 转账 
	* @param sourceName 转出账户名称 
	* @param targeName 转入账户名称 
	* @param money 转账金额 
	*/ 
	void transfer(String sourceName,String targeName,Float money);//增删改 
} 
 
 
package com.zzg.transaction.service.impl; 
 
import com.zzg.transaction.dao.IAccountDao; 
import com.zzg.transaction.entity.Account; 
import com.zzg.transaction.service.IAccountService; 
 
public class AccountServiceImpl implements IAccountService { 
	private IAccountDao accountDao; 
 
	public void setAccountDao(IAccountDao accountDao) { 
		this.accountDao = accountDao; 
	} 
 
	@Override 
	public Account findAccountById(Integer id) { 
		// TODO Auto-generated method stub 
		return accountDao.findAccountById(id); 
	} 
 
	@Override 
	public void transfer(String sourceName, String targeName, Float money) { 
		// TODO Auto-generated method stub 
		//1.根据名称查询两个账户 
		Account source = accountDao.findAccountByName(sourceName); 
		Account target = accountDao.findAccountByName(targeName); 
		//2.修改两个账户的金额 
		source.setMoney(source.getMoney()-money);//转出账户减钱 
		target.setMoney(target.getMoney()+money);//转入账户加钱 
		//3.更新两个账户 
		accountDao.updateAccount(source); 
		int i=1/0; 
		accountDao.updateAccount(target); 
	} 
 
} 

初始化数据库脚本

create table account( 
id int primary key auto_increment, 
name varchar(40), 
money float 
)character set utf8 collate utf8_general_ci;

演示代码和配置文件

package com.zzg.transaction; 
 
import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext; 
 
import com.zzg.transaction.entity.Account; 
import com.zzg.transaction.service.IAccountService; 
 
public class TransactionTest { 
 
	public static void main(String[] args) { 
		// TODO Auto-generated method stub 
		// 1.获取 Spring 容器 
		ApplicationContext ac = new ClassPathXmlApplicationContext("transactionXML.xml"); 
		IAccountService service = (IAccountService) ac.getBean("accountService"); 
		Account account = service.findAccountById(1); 
		System.out.println(account.toString()); 
		 
		service.transfer("张三", "李四", 100f); 
		 
	} 
 
} 
<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context" 
	xmlns:tx="http://www.springframework.org/schema/tx" 
	xmlns:aop="http://www.springframework.org/schema/aop" 
	xsi:schemaLocation="http://www.springframework.org/schema/beans  
 http://www.springframework.org/schema/beans/spring-beans.xsd 
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context.xsd 
 http://www.springframework.org/schema/tx  
 http://www.springframework.org/schema/tx/spring-tx.xsd 
 http://www.springframework.org/schema/aop 
 http://www.springframework.org/schema/aop/spring-aop.xsd"> 
	 
	<context:property-placeholder 
		location="classpath:jdbc.properties" /> 
 
	<!-- 配置 service --> 
	<bean id="accountService" 
		class="com.zzg.transaction.service.impl.AccountServiceImpl"> 
		<property name="accountDao" ref="accountDao"></property> 
	</bean> 
	<!-- 配置 dao --> 
	<bean id="accountDao" 
		class="com.zzg.transaction.dao.impl.AccountDaoImpl"> 
		<!-- 注入 dataSource --> 
		<property name="dataSource" ref="dataSource"></property> 
	</bean> 
 
	<!-- spring 默认内置数据源 --> 
	<bean id="dataSource" 
		class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
		<property name="driverClassName" value="${jdbc.driverClass}"></property> 
		<property name="url" value="${jdbc.url}"></property> 
		<property name="username" value="${jdbc.username}"></property> 
		<property name="password" value="${jdbc.password}"></property> 
	</bean> 
 
	<!-- 配置事务管理器 --> 
	<bean id="transactionManager" 
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
		<!-- 注入 DataSource --> 
		<property name="dataSource" ref="dataSource"></property> 
	</bean> 
 
	<!-- 事务配置 --> 
	<tx:advice id="txAdvice" 
		transaction-manager="transactionManager"> 
		<tx:attributes> 
			<!-- 指定方法名称:是业务核心方法 read-only:是否是只读事务。默认 false,不只读。 isolation:指定事务的隔离级别。默认值是使用数据库的默认隔离级别。  
				propagation:指定事务的传播行为。 timeout:指定超时时间。默认值为:-1。永不超时。 rollback-for:用于指定一个异常,当执行产生该异常时,事务回滚。产生其他异常,事务不回滚。  
				没有默认值,任何异常都回滚。 no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时,事务回 滚。没有默认值,任何异常都回滚。 --> 
			<tx:method name="*" read-only="false" 
				propagation="REQUIRED" /> 
			<tx:method name="find*" read-only="true" 
				propagation="SUPPORTS" /> 
		</tx:attributes> 
	</tx:advice> 
 
	<!-- 配置 aop --> 
	<aop:config> 
		<!-- 配置切入点表达式 --> 
		<aop:pointcut 
			expression="execution(* com.zzg.transaction.service.impl.*.*(..))" id="pt1" /> 
		<!-- 在 aop:config 标签内部:建立事务的通知和切入点表达式的关系 --> 
		<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1" /> 
	</aop:config> 
 
</beans>

第三  基于 注解 方式进行事务控制

核心代码:

package com.zzg.transaction.dao; 
 
import com.zzg.transaction.entity.Account; 
 
public interface IAccountDao { 
	/** 
	* 根据 id 查询账户信息 
	* @param id 
	* @return 
	*/ 
	Account findAccountById(Integer id); 
	/** 
	* 根据名称查询账户信息 
	* @return 
	*/ 
	Account findAccountByName(String name); 
	/** 
	* 更新账户信息 
	* @param account 
	*/ 
	void updateAccount(Account account); 
} 
 
 
package com.zzg.transaction.dao.impl; 
 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.util.List; 
 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.jdbc.core.JdbcTemplate; 
import org.springframework.jdbc.core.RowMapper; 
import org.springframework.stereotype.Repository; 
 
import com.zzg.transaction.dao.IAccountDao; 
import com.zzg.transaction.entity.Account; 
 
@Repository("accountDao") 
public class AccountDaoImpl implements IAccountDao { 
	@Autowired 
	private JdbcTemplate jdbcTemplate; 
	@Override 
	public Account findAccountById(Integer id) { 
		// TODO Auto-generated method stub 
		List<Account> list = jdbcTemplate.query("select * from account where id = ? ", new AccountRowMapper(), id); 
		return list.isEmpty() ? null : list.get(0); 
	} 
 
	@Override 
	public Account findAccountByName(String name) { 
		// TODO Auto-generated method stub 
		List<Account> list = jdbcTemplate.query("select * from account where name = ? ", new AccountRowMapper(), 
				name); 
		if (list.isEmpty()) { 
			return null; 
		} 
		if (list.size() > 1) { 
			throw new RuntimeException("结果集不唯一,不是只有一个账户对象"); 
		} 
		return list.get(0); 
	} 
 
	@Override 
	public void updateAccount(Account account) { 
		jdbcTemplate.update("update account set money = ? where id = ? ",account.getMoney(),account.getId()); 
	} 
 
	class AccountRowMapper implements RowMapper<Account> { 
 
		@Override 
		public Account mapRow(ResultSet rs, int rowNum) throws SQLException { 
			// TODO Auto-generated method stub 
			Account account = new Account(); 
			account.setId(rs.getInt("id")); 
			account.setName(rs.getString("name")); 
			account.setMoney(rs.getFloat("money")); 
			return account; 
		} 
 
	} 
 
} 
 
 
package com.zzg.transaction.service; 
 
import com.zzg.transaction.entity.Account; 
 
public interface IAccountService { 
	/** 
	* 根据 id 查询账户信息 
	* @param id 
	* @return 
	*/ 
	Account findAccountById(Integer id);//查 
	/** 
	* 转账 
	* @param sourceName 转出账户名称 
	* @param targeName 转入账户名称 
	* @param money 转账金额 
	*/ 
	void transfer(String sourceName,String targeName,Float money);//增删改 
} 
 
 
 
package com.zzg.transaction.service.impl; 
 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Service; 
import org.springframework.transaction.annotation.Propagation; 
import org.springframework.transaction.annotation.Transactional; 
 
import com.zzg.transaction.dao.IAccountDao; 
import com.zzg.transaction.entity.Account; 
import com.zzg.transaction.service.IAccountService; 
 
@Service("accountService") 
@Transactional(readOnly=true,propagation=Propagation.SUPPORTS) 
public class AccountServiceImpl implements IAccountService { 
	@Autowired 
	private IAccountDao accountDao; 
 
	@Override 
	public Account findAccountById(Integer id) { 
		// TODO Auto-generated method stub 
		return accountDao.findAccountById(id); 
	} 
 
	@Override 
	public void transfer(String sourceName, String targeName, Float money) { 
		// TODO Auto-generated method stub 
		//1.根据名称查询两个账户 
		Account source = accountDao.findAccountByName(sourceName); 
		Account target = accountDao.findAccountByName(targeName); 
		//2.修改两个账户的金额 
		source.setMoney(source.getMoney()-money);//转出账户减钱 
		target.setMoney(target.getMoney()+money);//转入账户加钱 
		//3.更新两个账户 
		accountDao.updateAccount(source); 
		int i=1/0; 
		accountDao.updateAccount(target); 
	} 
 
} 
 
 
package com.zzg.transaction.entity; 
 
import java.io.Serializable; 
 
@SuppressWarnings("serial") 
public class Account implements Serializable { 
	private Integer id; 
	private String name; 
	private Float money; 
 
	public Integer getId() { 
		return id; 
	} 
 
	public void setId(Integer id) { 
		this.id = id; 
	} 
 
	public String getName() { 
		return name; 
	} 
 
	public void setName(String name) { 
		this.name = name; 
	} 
 
	public Float getMoney() { 
		return money; 
	} 
 
	public void setMoney(Float money) { 
		this.money = money; 
	} 
 
	@Override 
	public String toString() { 
		return "Account [id=" + id + ", name=" + name + ", money=" + money + "]"; 
	} 
 
} 

演示代码和配置文件

package com.zzg.transaction; 
 
import org.springframework.context.ApplicationContext; 
import org.springframework.context.support.ClassPathXmlApplicationContext; 
 
import com.zzg.transaction.entity.Account; 
import com.zzg.transaction.service.IAccountService; 
 
public class TransactionTest { 
 
	public static void main(String[] args) { 
		// TODO Auto-generated method stub 
		// 1.获取 Spring 容器 
		ApplicationContext ac = new ClassPathXmlApplicationContext("transactionAnnotation.xml"); 
		IAccountService service = (IAccountService) ac.getBean("accountService"); 
		Account account = service.findAccountById(1); 
		System.out.println(account.toString()); 
		 
		service.transfer("张三", "李四", 100f); 
		 
	} 
 
} 
<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context" 
	xmlns:tx="http://www.springframework.org/schema/tx" 
	xmlns:aop="http://www.springframework.org/schema/aop" 
	xsi:schemaLocation="http://www.springframework.org/schema/beans  
 http://www.springframework.org/schema/beans/spring-beans.xsd 
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context.xsd 
 http://www.springframework.org/schema/tx  
 http://www.springframework.org/schema/tx/spring-tx.xsd 
 http://www.springframework.org/schema/aop 
 http://www.springframework.org/schema/aop/spring-aop.xsd"> 
 
	<!-- 配置 spring 创建容器时要扫描的包 --> 
	<context:component-scan 
		base-package="com.zzg.transaction"></context:component-scan> 
 
	<context:property-placeholder 
		location="classpath:jdbc.properties" /> 
 
 
	<!-- 配置 JdbcTemplate --> 
	<bean id="jdbcTemplate" 
		class="org.springframework.jdbc.core.JdbcTemplate"> 
		<property name="dataSource" ref="dataSource"></property> 
	</bean> 
 
	<!-- spring 默认内置数据源 --> 
	<bean id="dataSource" 
		class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
		<property name="driverClassName" value="${jdbc.driverClass}"></property> 
		<property name="url" value="${jdbc.url}"></property> 
		<property name="username" value="${jdbc.username}"></property> 
		<property name="password" value="${jdbc.password}"></property> 
	</bean> 
 
	<!-- 配置事务管理器 --> 
	<bean id="transactionManager" 
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
		<!-- 注入 DataSource --> 
		<property name="dataSource" ref="dataSource"></property> 
	</bean> 
 
	<!-- 开启 spring 对注解事务的支持 --> 
	<tx:annotation-driven 
		transaction-manager="transactionManager" /> 
 
</beans>

第四  基于 XML 方式进行事务控制,核心步骤说明:

第一步:配置事务管理器 
 
<!-- 配置一个事务管理器 -->  
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
    <!-- 注入 DataSource -->  
    <property name="dataSource" ref="dataSource"></property> 
</bean> 
 
第二步:配置事务的通知引用事务管理器 
 
<!-- 事务的配置 --> 
 <tx:advice id="txAdvice" transaction-manager="transactionManager"> 
 </tx:advice> 
 
第三步:配置事务的属性 
 
<!--在 tx:advice 标签内部 配置事务的属性 -->  
<tx:attributes> 
    <!-- 指定方法名称:是业务核心方法 
        read-only:是否是只读事务。默认 false,不只读。 
        isolation:指定事务的隔离级别。默认值是使用数据库的默认隔离级别。 
        propagation:指定事务的传播行为。 
        timeout:指定超时时间。默认值为:-1。永不超时。 
        rollback-for:用于指定一个异常,当执行产生该异常时,事务回滚。产生其他异常,事务不回滚。 
            没有默认值,任何异常都回滚。 
        no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时,事务回 
            滚。没有默认值,任何异常都回滚。 
    -->  
    <tx:method name="*" read-only="false" propagation="REQUIRED"/> 
    <tx:method name="find*" read-only="true" propagation="SUPPORTS"/> 
</tx:attributes> 
 
第四步:配置 AOP 切入点表达式 
 
<!-- 配置 aop --> 
<aop:config> 
    <!-- 配置切入点表达式 --> 
     <aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))" 
        id="pt1"/> 
</aop:config> 
 
第五步:配置切入点表达式和事务通知的对应关系 
 
<!-- 在 aop:config 标签内部:建立事务的通知和切入点表达式的关系 --> 
 <aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>

第五  基于 注解 方式进行事务控制,核心步骤说明:

 第一步:配置事务管理器并注入数据源 
 
<!-- 配置事务管理器 -->  
<bean id="transactionManager" 
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
    <property name="dataSource" ref="dataSource"></property> 
</bean> 
 
第二步:在业务层使用@Transactional 注解 
 
@Service("accountService") 
@Transactional(readOnly=true,propagation=Propagation.SUPPORTS) 
public class AccountServiceImpl implements IAccountService{ 
        ****** 
} 
 
第三步:在配置文件中开启 spring 对注解事务的支持 
 
<!-- 开启 spring 对注解事务的支持 -->  
<tx:annotation-driven transaction-manager="transactionManager"/>

 

声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号