1. 程式人生 > >使用spring jdbcTemplate和dbcp操作資料庫及事務配置

使用spring jdbcTemplate和dbcp操作資料庫及事務配置

程式碼結構及jar包

ServiceClass.java

package com.orange.test;

import java.sql.Types;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.management.RuntimeErrorException;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional	//增加事務
public class ServiceClass {
	@Autowired	//注入dataSource屬性
	private DataSource dataSource;
	private JdbcTemplate jdbcTemplate;	
	
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	//例項化ServiceClass類後執行init()方法初始化jdbcTemplate
	@PostConstruct  
	public void init(){
		System.out.println("初始化jdbcTemplate");
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}
	
	@Transactional(propagation=Propagation.REQUIRED)	//預設事務,可以不寫
	public void save(){
		jdbcTemplate.update("insert into spring (name) value(?)", new Object[]{"sa"},new int[]{	Types.VARCHAR});
	}
	@Transactional(propagation=Propagation.REQUIRED)	//預設事務,可以不寫
	public void update(){
		jdbcTemplate.update("update spring set name = ? where id = ?", new Object[]{"A",1},new int[]{	Types.VARCHAR,Types.INTEGER});
	}
	/**
	 * 預設只對unchecked異常有效 
	 * Error和RuntimeException及其子類成為未檢查異常(unchecked)
	 * 其它異常成為已檢查異常(checked)
	 */
	@Transactional(rollbackFor=Exception.class)
	public void delete() throws Exception{
		jdbcTemplate.update("delete from spring where id = ?", new Object[]{11},new int[]{Types.INTEGER});
//		System.out.println(1/0);	//執行異常
		throw new Exception("異常");
	}
	public String getData(){
		return (String)jdbcTemplate.queryForObject("select * from spring where id = ?", new Object[]{1},new int[]{Types.INTEGER}, new TestRowMapper());
	}
	/**
	 * 第一方法種查詢所有
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)	//不啟用事務
	public List<String> getAll(){
		return (List<String>)jdbcTemplate.query("select * from spring ",new TestRowMapper());
	}
	/**
	 * 第二方法種查詢所有
	 */
	@Transactional(propagation=Propagation.NOT_SUPPORTED)	//不啟用事務
	public List<String> getAllList(){
		return (List<String>)jdbcTemplate.queryForList("select * from spring ");
	}
}


TestRowMapper.java

package com.orange.test;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;

public class TestRowMapper implements RowMapper{

	public Object mapRow(ResultSet rs, int arg1) throws SQLException {
		String name = rs.getString("name");
		return name;
	}
}


Test.java

package com.orange.test;

import java.util.List;

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

public class Test {

	public static void main(String[] args) {
		ApplicationContext context1 = new ClassPathXmlApplicationContext("beans.xml");
		ServiceClass service= (ServiceClass)context1.getBean("serviceClass");
//		service.save();
		List<String> list =  service.getAll();		
		System.out.println(list);
		List<String> list2 =  service.getAllList();
		System.out.println(list2);
		//執行刪除
		try {
			service.delete();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
//		list =  service.getAll();
//		System.out.println(list);
	}
}

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"
       xmlns:context="http://www.springframework.org/schema/context" 
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
	
	<!-- 對 com.orange.test 下的類掃描交給spring管理-->        
    <context:component-scan base-package="com.orange.test"></context:component-scan> 
	
	<!-- 指定spring jdbc屬性檔案位置 -->
	 <context:property-placeholder location="classpath:jdbc.properties"/>
	 <!-- 資料來源 -->
  	 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
	    <property name="driverClassName" value="${driverClassName}"/>
	    <property name="url" value="${url}"/>
	    <property name="username" value="${username}"/>
	    <property name="password" value="${password}"/>
	   <!--initialSize: 初始化連線-->  
		<property name="initialSize" value="5"/>  
		<!--maxIdle: 最大空閒連線-->  
		<property name="maxIdle" value="10"/>  
		<!--minIdle: 最小空閒連線-->  
		<property name="minIdle" value="5"/>  
		<!--maxActive: 最大連線數量-->  
		<property name="maxActive" value="15"/>  
		<!--removeAbandoned: 是否自動回收超時連線-->  
		<property name="removeAbandoned" value="true"/>  
		<!--removeAbandonedTimeout: 超時時間(以秒數為單位)-->  
		<property name="removeAbandonedTimeout" value="180"/>  
		<!--maxWait: 超時等待時間以毫秒為單位 6000毫秒/1000等於60秒-->  
		<property name="maxWait" value="3000"/> 
		<!-- 用來驗證從連線池取出的連線,在將連線返回給呼叫者之前.如果指定,則查詢必須是一個SQL SELECT並且必須返回至少一行記錄 --> 
		<property name="validationQuery">  
		<value>SELECT 1</value>  
		</property>  
	 </bean>
	 
	 <!-- spring使用的管理器 -->
	 <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  	   <property name="dataSource" ref="dataSource"/>
    </bean>
    <!-- 使用註解配置spring事務 -->
    <tx:annotation-driven transaction-manager="txManager"/>

</beans>


jdbc.properties

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/dbname?useUnicode=true&characterEncoding=UTF-8
username=root
password=123456
以上是使用註解的方式配置事務,如要要使用xml配置只需在beans.xml增加:
<!-- 定義切面類,需要使用事務 -->
    <aop:config>
	  	<aop:pointcut id="transactionPointcut" expression="execution(* com.orange.test.ServiceClass.*(..))"/>
	  	<aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/>
	</aop:config> 
	<tx:advice id="txAdvice" transaction-manager="txManager">
		  <tx:attributes>
		  <!-- 方法名是get開頭的不適用事務 -->
		    <tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/>
		    <!-- 其實使用預設事務 -->
		    <tx:method name="*"/>
		  </tx:attributes>
	</tx:advice>