代码结构及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>