spring的jdbc及事务管理

步骤:
1.编写properties和sprin配置文件;
1.1加载jdbc.properties文件
1.2获取配置数据源信息(dbcp数据连接池)
1.3加载spring的事物管理器
1.4启动Spring注解方式事物管理
2.编写java代码,在service层的处理类上进行@Transactional注解
2.1得到private JdbcTemplate jdbcTemplate,并生成set方法;
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
2.2通过jdbcTemplate对象的update方法进行增删改,其中,对于返回一个对象的查找,我们仍用update方法,
不过,需要一个new UserServiceRowMapper()对象,此对象将结果集数据转换为需要的对象格式;对于返回集合的查找,我们使用query方法,


示例:
properties文件:
username=xiaogang
url=jdbc\:oracle\:thin\:@127.0.0.1\:1521\:orcl
driverClassName=oracle.jdbc.driver.OracleDriver
initialSize=1
minIdle=2
maxIdle=3
maxActive=5
password=xiaogang


spring配置文件:
<?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">
	
	<!-- 加载jdbc.properties文件 -->
	<context:property-placeholder location="classpath:jdbc.properties"/>
	
	<!-- 配置数据源(dbcp数据连接池) -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
	  <property name="username" value="${username}"/>
	  <property name="password"  value="${password}"/>
	  <property name="url"  value="${url}"/>
	  <property name="driverClassName"  value="${driverClassName}"/>
	  <property name="initialSize"  value="${initialSize}"/>
	  <property name="minIdle"  value="${minIdle}"/>
	  <property name="maxIdle"  value="${maxIdle}"/>
	  <property name="maxActive"  value="${maxActive}"/>
	</bean>
	
	<bean id="userService" 
				class="com.xiaogang.user.service.impl.UserServiceImpl">
		<property name="dataSource" ref="dataSource" />
	</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>



java处理代码:
实体类省略;
service层代码事务处理类:

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


import javax.sql.DataSource;


import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


import com.xiaogang.pojo.User;
import com.xiaogang.user.service.IUserService;


@Transactional
public class UserServiceImpl implements IUserService {


	private JdbcTemplate jdbcTemplate;


	public void setDataSource(DataSource dataSource) {
		this.jdbcTemplate = new JdbcTemplate(dataSource);
	}


	@Override
	public boolean save(User user) {
		return 
		  this.jdbcTemplate
		       .update("insert into user_info values(userseq.nextval,?)", 
				 new Object[]{user.getName()}, 
				  new int[]{Types.VARCHAR})>0?true:false;
	}


	@Override
	@Transactional(rollbackFor=Exception.class)
	public boolean removeUserById(int id) throws Exception {
		return 
		  this.jdbcTemplate
		       .update("delete from user_info where id=?", 
				 new Object[]{id}, 
				  new int[]{Types.INTEGER})>0?true:false;
		  
	}


	@Override
	public boolean modify(User user) {
		return 
		  this.jdbcTemplate
		       .update("update user_info set name=? where id=?", 
				 new Object[]{user.getName(),user.getId()}, 
				  new int[]{Types.VARCHAR,Types.INTEGER})>0?true:false;
	}


	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	@Override
	public User findUserById(int id) {
		return (User)
			 this.jdbcTemplate.queryForObject("select * from user_info where id=?", 
				new Object[]{id}, 
				  new int[]{Types.INTEGER}, 
					new UserServiceRowMapper());//把结果集数据转换为需要的对象格式
		
	}
	@Transactional(propagation=Propagation.NOT_SUPPORTED,readOnly=true)
	@Override
	@SuppressWarnings("unchecked")
	public List<User> searchUser() {
		return this.jdbcTemplate.query("select * from user_info",new UserServiceRowMapper());
	}
}


结果集数据转换为需要的对象格式的类:
import java.sql.ResultSet;
import java.sql.SQLException;


import org.springframework.jdbc.core.RowMapper;


import com.xiaogang.pojo.User;


public class UserServiceRowMapper implements RowMapper {


	@Override
	public Object mapRow(ResultSet rs, int index) throws SQLException {
		//把查询结果集数据转换为com.xiaogang.pojo.User类对象
		User user = new User(rs.getInt("id"),rs.getString("name"));
		return user;
	}


}

测试类:


import java.util.List;

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

import com.xiaogang.pojo.User;
import com.xiaogang.user.service.IUserService;

public class SpringJdbcTest {

	static ApplicationContext ctx;
	
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		ctx = new ClassPathXmlApplicationContext("beans.xml");
	}
	
	@Test
	public void testSave(){
		User u = new User();
		u.setName("黄盖");
		
		IUserService userService = (IUserService)ctx.getBean("userService");
		userService.save(u);		
		
	}
	@Test
	public void findUserByIdTest(){
		IUserService userService = (IUserService)ctx.getBean("userService");
		User user = userService.findUserById(3);
		System.out.println(user);
		
	}
	
	@Test
	public void modifyTest(){
		IUserService userService = (IUserService)ctx.getBean("userService");
		User user = userService.findUserById(3);
		System.out.println(user);
		
		user.setName("周瑜");
		userService.modify(user);
		
	}
	
	@Test
	public void removeUserByIdTest(){
		IUserService userService = (IUserService)ctx.getBean("userService");
		try {
			userService.removeUserById(2);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Test
	public void searchUserTest(){
		IUserService userService = (IUserService)ctx.getBean("userService");
		List<User> users=userService.searchUser();
		for(User u: users){
			System.out.println(u);
		}
	}
	

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值