Spring声明式事务管理(基于xml的方式)

一、UserDao类,提供save,update,delete,query方法

<span style="font-size:18px;">package com.seven.spring.p_jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

@Repository("userDao")
public class UserDao {
	@Resource
	private JdbcTemplate jdbcTemplate;
	/**
	 * 保存用户
	 * @param user
	 */
    public void save(final User user){
//    	jdbcTemplate.execute(new ConnectionCallback() {
//			
//			public Object doInConnection(Connection con) throws SQLException,
//					DataAccessException {
//				String sql="insert into t_user(uname,age) values (?,?)";
//				PreparedStatement ps = con.prepareStatement(sql);
//				ps.setString(1, user.getUname());
//				ps.setInt(2, user.getAge());
//				ps.execute();
//				return null;
//			}
//		});
    	
    	//代码简化
    	String sql="insert into t_user(uname,age) values (?,?)";
    	jdbcTemplate.update(sql,new Object[]{user.getUname(),user.getAge()});
    	
    }
    /**
     * 删除用户
     * @param id
     */
    public void delete(Integer id){
    	String sql = "delete from t_user where id=?";
    	jdbcTemplate.update(sql, new Object[]{id});
    }
    /**
     * 用户更新
     * @param user
     */
    public void update(User user){
    	String sql = "update t_user set uname=?,age=? where id=?";
    	jdbcTemplate.update(sql, new Object[]{user.getUname(),user.getAge(),user.getId()});
    	
    }
    /**
     * 通过id查找一个用户
     * @param id
     * @return
     */
    public User findById(final Integer id){
    	String sql ="select uname,age from t_user where id=?";
    	return (User) jdbcTemplate.queryForObject(sql, new Object[]{id}, new RowMapper() {
			@Override
			public Object mapRow(ResultSet rs, int arg1) throws SQLException {
				String name = rs.getString(1);
				int age = rs.getInt(2);
				return new User(id,name,age);
			}
		});
    	
    }
    /**
     * 查询所有
     * @return
     */

	public List<User> findAll(){
    	String sql = "select id,uname,age from t_user";
    	return jdbcTemplate.query(sql, new RowMapper() {
			public Object mapRow(ResultSet rs, int arg1) throws SQLException {
				int id = rs.getInt(1);
				String name = rs.getString(2);
			    int age = rs.getInt(3);
				return new User(id, name, age);
			}
		});
    }
    
    /**
     * 查询所有(支持分页)
     * @param fristRes
     * @param MaxRes
     * @return
     */
    public QueryResult findAll(int fristRes,int MaxRes){
    	int count = jdbcTemplate.queryForInt("select count(*) from t_user");
    	
    	List list = jdbcTemplate.query("select * from t_user limit ?,?",
    			new Object[]{fristRes,MaxRes},new RowMapper() {
					@Override
					public Object mapRow(ResultSet res, int arg1) throws SQLException {
						int id = res.getInt(1);
						String name = res.getString(2);
						int age = res.getInt(3);
						return new User(id, name, age);
					}
				});
    			
    	return new QueryResult(count, list);
    }
    /**
     * 查询总数据
     * @return
     */
    public int getCount(){
    	String sql = "select count(*) from t_user";
    	return jdbcTemplate.queryForInt(sql);
    }
}
</span>
二、applicationContext.xml

<span style="font-size:18px;"><?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-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/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
  
   <!-- 通过注解的方式配置bean,指定扫描的包 -->
   <context:component-scan base-package="com.seven.spring.p_jdbc"></context:component-scan>
   
   <!-- 加载jdbc.properties配置文件 -->
   <context:property-placeholder location="classpath:com/seven/spring/p_jdbc/jdbc.properties"/>
   
   
   <!-- 1、配置数据库连接池 -->
   <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
	     <!-- 基本的连接信息 -->
	     <property name="driverClass" value="${driverClass}"></property>
	     <property name="jdbcUrl" value="${jdbcUrl}"></property>
	     <property name="user" value="${username}"></property>
	     <property name="password" value="${password}"></property>
	     <!-- 一些管理的配置 -->
	     <!-- 初始化时获取3个连接 ,取值应该在minPoolSize和maxPoolSize之间。默认是3-->
	     <property name="initialPoolSize" value="3"></property>
	     <!-- 连接池中最小的连接数 ,默认是3-->
	     <property name="minPoolSize" value="3"></property>
	     <!-- 连接池中最大的连接数,默认为15 -->
	     <property name="maxPoolSize" value="5"></property>
	     <!-- 当数据库连接池中的连接耗尽的时候c3p0一次同时获取的连接数,默认值为3 -->
	     <property name="acquireIncrement" value="3"></property>
	     <!-- 最大空闲时间, 1800秒内未使用则连接被丢弃,若值为0则永不丢弃,默认值为0-->
	     <property name="maxIdleTime" value="1800"></property>
   </bean>
   
   <!-- 配置jdbcTemplate -->
   <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">
      <!-- 这里需要引入 一个datasource -->
      <property name="dataSource" ref="dataSource"></property>
   </bean>
   
   <!-- 声明通知 -->
   <tx:advice id="MyTransactionManager" transaction-manager="transactionManager">
      <tx:attributes>
      <!-- 对于以save,update或者delete开头的方法,使用正常的事务,其他方法都使用只读事务 
           read-only表示是否是只读,默认为false
      -->
        <tx:method name="save*"/>
        <tx:method name="update*"/>
        <tx:method name="delete*"/>
        <tx:method name="*" read-only="true"/>
      </tx:attributes>
   </tx:advice>
   
   <!-- 声明切面 -->
   <aop:config>
    <aop:advisor advice-ref="MyTransactionManager" pointcut="execution(* com.seven.spring.p_jdbc.*Dao.*(..))"/>
   </aop:config>
</beans></span>

UserTest测试类

<span style="font-size:18px;">package com.seven.spring.p_jdbc;

import static org.junit.Assert.*;

import java.util.List;

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

public class UserDaoTest {
	//加载全局的配置文件
	private ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml",getClass());
	//从配置文件中获取userDao的bean
	private UserDao userDao = (UserDao) ac.getBean("userDao");
    
	/**
	 * 测试保存一个数据
	 */
	@Test
	public void testSave_1() {
		User user= new User();
		user.setUname("小胖子22");
		user.setAge(20);
		userDao.save(user);
	}
	@Test
	public void testSave_25() {
		for(int i=1;i<=25;i++){
			User user= new User();
			user.setUname("test"+i);
			user.setAge(20);
			userDao.save(user);
		}

	}
    
	/**
	 * 测试删除
	 */
	@Test
	public void testDelete() {
		userDao.delete(1);
	}
    
	/**
	 * 测试更新
	 */
	@Test
	public void testUpdate() {
		User user= new User();
		user.setId(2);
		user.setUname("小胖子222");
		user.setAge(20);
		userDao.update(user);
		
	}
    
	/**
	 * 测试通过id查询
	 */
	@Test
	public void testFindById() {
		User user = userDao.findById(2);
		System.out.println(user);
	}
    /**
     * 测试查询所有
     */
	@Test
	public void testFindAll() {
		List<User> users = userDao.findAll();
		for(User user:users){
			System.out.println(user);
		}
		
	}
     
	/**
	 * 测试分页
	 */
	@Test
	public void testFindAllIntInt() {
//		QueryResult queryResult=userDao.findAll(0, 10);//第一页
		QueryResult queryResult=userDao.findAll(10, 10);//第二页
//		QueryResult queryResult=userDao.findAll(20, 10);//第三页
		System.out.println("总记录为:"+queryResult.getCount());
		for(User user:(List<User>)queryResult.getList()){
			System.out.println(user);
		}
		
	}
    
	/**
	 * 测试查询总数
	 */
	@Test
	public void testGetCount() {
		System.out.println(userDao.getCount());
	}

}</span>
这样就对UserDao中, 对于以save,update或者delete开头的方法,使用正常的事务,其他方法都使用只读事务 。( read-only表示是否是只读,默认为false)





  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值