1. 程式人生 > >Spring學習——JDBC事務

Spring學習——JDBC事務

spring 事務 主要是指jdbc事務

當一組事務執行完時,需要提交commit,才能在資料庫中完成執行, 當一組事務中的某個錯誤時候,需要撤銷回滾rollback()

當SQL執行報錯時候,呼叫rollback函式,commit操作取消
當沒有commit操作時候,資料庫資料不會發生改變,rollback操作無效

1、JdbcTemplate.query/update ->  
2、PlatformTransactionManager.commit ->  
3、PlatformTransactionManager.rollback

1執行成功後,JdbcTemplate內資料物件發生改變,但資料庫資料未發生改變
2執行成功後,JdbcTemplate內資料提交到資料庫,資料庫資料發生改變
3執行成功後,資料資料還原到commit之前

Beans.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" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd ">

   <!-- 初始化資料庫配置檔案 -->
   <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
      <property name="url" value="jdbc:mysql://localhost:3306/test"/>
      <property name="username" value="root"/>
      <property name="password" value=""/>
   </bean>
	
	<!-- 配置事務	 -->
   	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      	<property name="dataSource"  ref="dataSource" />    
   	</bean>	
	
	<!-- 配置jdbc實現類 -->
   	<bean id="userJdbcTemplate" class="com.spring.transaction.demo.UserJdbcTemplate" >
   		<!-- 注入資料庫配置檔案 -->
   		<property name="dataSource"  ref="dataSource" /> 
   		<property name="transactionManager"  ref="transactionManager" />    
   	</bean>
   
   
</beans>

核心配置類

package com.spring.transaction.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

public class UserJdbcTemplate{

	private JdbcTemplate jdbcTemplate;
	private DataSource dataSource;
	private PlatformTransactionManager ptm;
	
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}
	
	public void setTransactionManager(PlatformTransactionManager ptm){
		this.ptm = ptm;
	}
	
	public void update(int id){
		TransactionDefinition def = new DefaultTransactionDefinition();
		TransactionStatus status = ptm.getTransaction(def);
		try {
			String sql = "insert into user(id,username,password) values("+id+",'lg','123456')";
			System.out.println("sql執行:"+sql);
			jdbcTemplate.update(sql);
			
			sql = "insert into user(id,username,password) values("+(id-1)+",'zdj','123456')";
			System.out.println("sql執行:"+sql);
			jdbcTemplate.update(sql);
			
			sql = "update user set username='zh' where id = 2";
			System.out.println("sql執行:"+sql);
			jdbcTemplate.update(sql);
			
			ptm.commit(status);
		} catch (DataAccessException e) {
			System.out.println("回滾");
			ptm.rollback(status);
			e.printStackTrace();
		}
	}
	
	public List<UserPO> queryAll(){
		String sql = "select * from user";
		List<Map<String, Object>> mapList = jdbcTemplate.queryForList(sql);
		List<UserPO> list = new ArrayList();
		for (int i = 0; i < mapList.size(); i++) {
			UserPO user = new UserPO();
			user.setId((Integer)mapList.get(i).get("id"));
			user.setUsername(mapList.get(i).get("username").toString());
			user.setPassword(mapList.get(i).get("password").toString());
			list.add(user);
		}
		return list;
	}
}

SpringMain

package com.spring.transaction.demo;

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

public class SpringMain {
	public static void main(String[] args){
		ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");
		UserJdbcTemplate ujt = (UserJdbcTemplate) context.getBean("userJdbcTemplate");
		System.out.println("--------第一次查詢資料庫-----------");
		System.out.println(ujt.queryAll().toString());
		
		System.out.println("---------正常執行-----------");
		ujt.update(2);
		System.out.println("--------第二次查詢資料庫-----------");
		System.out.println(ujt.queryAll().toString());
		
		System.out.println("---------錯誤執行-----------");
		ujt.update(3);
		System.out.println("--------第二次查詢資料庫-----------");
		System.out.println(ujt.queryAll().toString());
		
	}
}