19、(知識篇)Spring使用事務Transation

/**

* spring事務管理:

* 1、指定transactionmanager

* <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

* <property name="dataSource"ref="dataSource"></property>

* </bean>

*

* 2.1、指定通過註解設置事務

* <tx:annotation-driven/>

*

*  2.2、指定通過xml設置事務

<!-- 

使用xml配置服務

1、使用tx:advice指定需要使用事務的方法

1、1可以指定方法/匹配方法/* 設置需要使用事務

2、需要用aop聲明切點,然後配置事務advice-ref爲事務advice關聯

<tx:advice id="txad" transaction-manager="transactionManager">

<tx:attributes> <tx:method name="*"/></tx:attributes>

</tx:advice>

<aop:config>

<aop:pointcut expression="execution(*  com.spring.service.UserService.*(..))" id="userServiceTrancation"/>

<aop:advisor advice-ref="txad"pointcut-ref="userServiceTrancation"/>

</aop:config>-->

*

*

* 3、事務傳播行爲/隔離級別/設置回滾類/只讀設置 (參考userservice

* @Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.READ_COMMITTED,readOnly=true,rollbackFor={Exception.class})

* @param args

*/



測試類:

package com.spring.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.service.UserService;
import com.spring.vo.User;

public class Test {
	
	/**
	 * spring事務管理:
	 * 	
	 * 1、指定transactionmanager
	 * <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	 *		<property name="dataSource" ref="dataSource"></property>
	 *	</bean>
	 *	
	 *	2.1、指定通過註解設置事務
	 *	<tx:annotation-driven/>
	 *	
	 *  2.2、指定通過xml設置事務
	 *  	<!-- 
			使用xml配置服務
			1、使用tx:advice指定需要使用事務的方法
				1、1可以指定方法/匹配方法/* 設置需要使用事務
			2、需要用aop聲明切點,然後配置事務advice-ref爲事務advice關聯
				
			<tx:advice id="txad" transaction-manager="transactionManager">
				<tx:attributes> <tx:method name="*"/> </tx:attributes>
			</tx:advice>
			<aop:config>
				<aop:pointcut expression="execution(*  com.spring.service.UserService.*(..))" id="userServiceTrancation"/>
				<aop:advisor advice-ref="txad" pointcut-ref="userServiceTrancation"/>
			</aop:config> -->
	 *
	 *
	 * 	3、事務傳播行爲/隔離級別/設置回滾類/只讀設置 (參考userservice)
	 * 		@Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.READ_COMMITTED,readOnly=true,rollbackFor={Exception.class})
	 * 
	 * @param args
	 */
	
	public static void main(String[] args) {
		
		ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
		
		UserService userService = ctx.getBean(UserService.class);
		
		
		//修改
		userService.updateTwoUser(new User(1, "Flash", 1), new User(2, "SuperMan", 1));
	
	}
}

持久層類:

package com.spring.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.spring.dao.UserDao;
import com.spring.vo.User;

@Service
public class UserService {

	@Autowired
	private UserDao userDao;

	
	/**
	 * 1、事務傳播行爲:
	 *  	默認propagation=Propagation.REQUIRED 
	 *  	例如執行兩次修改,第一次修改成功,第二次修改失敗,則都會視爲失敗
	 * 		如果設置爲:Propagation.REQUIRES_NEW 則外面事務會掛起
	 * 		例如執行兩次修改,第一次修改成功,第二次修改失敗,則第一次會提交成功
	 * 
	 * 2、事務隔離級別:
	 * 		isolation:設置相關讀只提交/髒讀/幻讀等值
	 * 
	 * 4、只讀:
	 * 		readonly:如果事務只讀操作,設置該值會相對提高性能
	 * 
	 * 5、回滾:
	 * 		noRollbackFor:(類)
	 * 		noRollbackForClassName:(全類名)指定不回滾的異常
	 * 		rollbackFor:(指定回滾的異常)
	 * 		rollbackForClassName
	 * 		例如 rollbackFor={Exception.class}
	 * 
	 * @Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.READ_COMMITTED,readOnly=true,rollbackFor={Exception.class})
	 */
	@Transactional
	public void updateTwoUser(User user1,User user2){
		
		int row = userDao.updateUser(user1);
		System.out.println("row == "+row);
		
		user2.setSex(user2.getSex()/0);
		int row2 = userDao.updateUser(user2);
		System.out.println("row2 == "+row2);
	}
	
}

package com.spring.dao;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.spring.vo.User;

@Repository
public class UserDao {
	
	@Autowired
	private JdbcTemplate template;
	
	/**
	 * 更新
	 * @param user
	 * @return
	 */
	public int updateUser(User user){
		String sql = " update User set userName = ? ,sex = ? where id = ? ";
		return template.update(sql, user.getUserName(),user.getSex(),user.getId());
	}
	

	/**
	 * 查找返回一個對象
	 * 採用queryForObject(String sql, RowMapper<User> rowMapper)
	 * 需要傳入RowMapper對象
	 * @param userId
	 * @return
	 */
	public User getUserById(int userId){
		String sql = " select * from User where id = ? ";
		RowMapper<User> userMapper = new BeanPropertyRowMapper<>(User.class);
		return template.queryForObject(sql, userMapper,userId);
	}
	
	
}

package com.spring.vo;

import org.springframework.stereotype.Component;

@Component
public class User {
	private int id;
	private String userName;
	private int sex;
	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	public User(int id, String userName, int sex) {
		super();
		this.id = id;
		this.userName = userName;
		this.sex = sex;
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public int getSex() {
		return sex;
	}
	public void setSex(int sex) {
		this.sex = sex;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", userName=" + userName + ", sex=" + sex + "]";
	}
	
}

applicationContext.xml

<?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-4.3.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
	
	<context:component-scan base-package="com.spring"></context:component-scan>
	<!-- 指定數據源配置properties -->
	<context:property-placeholder location="classpath:db.properties"/>
	
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${driverClass}" ></property>
		<property name="jdbcUrl" value="${url}" ></property>
		<property name="user" value="${userName}" ></property>
		<property name="password" value="${password}"></property>
	</bean>
	
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"></property>
	</bean>
	<!-- 指定用註解管理事務 -->
	<tx:annotation-driven/>
	
	
	<!-- 
	使用xml配置服務
	1、使用tx:advice指定需要使用事務的方法
		1、1可以指定方法/匹配方法/* 設置需要使用事務
	2、需要用aop聲明切點,然後配置事務advice-ref爲事務advice關聯
		
	<tx:advice id="txad" transaction-manager="transactionManager">
		<tx:attributes>
			指定方法
			<tx:method name="updateTwoUser" propagation="REQUIRES_NEW"/> 
			
			匹配方法 
			<tx:method name="update*" />
			
			<tx:method name="*"/>
		</tx:attributes>
	</tx:advice>
	<aop:config>
		<aop:pointcut expression="execution(*  com.spring.service.UserService.*(..))" id="userServiceTrancation"/>
		<aop:advisor advice-ref="txad" pointcut-ref="userServiceTrancation"/>
	</aop:config> -->
	
	
</beans>

db.properties

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/Test
userName=root
password=root


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章