现在的位置: 首页 > 综合 > 正文

Spring视频学习(八)整合JDBC

2012年01月18日 ⁄ 综合 ⁄ 共 7663字 ⁄ 字号 评论关闭

1.配置命名空间

<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 
	                  ">

2.配置数据源                  
<!-- 配置数据源 -->  
  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
    <property name="driverClassName" value="com.mysql.Driver"/>  
    <property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8"/>  
    <property name="username" value="root"/>  
    <property name="password" value=""/>  
     <!-- 连接池启动时的初始值 -->  
     <property name="initialSize" value="1"/>  
     <!-- 连接池的最大值 -->  
     <property name="maxActive" value="500"/>  
     <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->  
     <property name="maxIdle" value="2"/>  
     <!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->  
     <property name="minIdle" value="1"/>  
  </bean> 

3.配置事务

  <!-- 配置事务-->   
 <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">   
    <property name="dataSource" ref="dataSource"/>   
  </bean>   
  <!-- 采用@Transactional注解方式来使用事务 -->   
  <tx:annotation-driven transaction-manager="txManager"/>  

4.添加业务bean

 <bean id="personService" class="com.persia.service.impl.PersonServiceImpl">
    <property name="ds" ref="dataSource"></property>
  </bean>
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public class PersonServiceImpl implements IPersonService {

//	private DataSource ds;
	private JdbcTemplate jdbcTemplate;
	
	public void setDs(DataSource ds) {
		this.jdbcTemplate=new JdbcTemplate(ds);
	}

	@Override
	public void delete(Integer id) {
		// TODO Auto-generated method stub
		jdbcTemplate.update("delete from person where id=?", new Object[]{id},   
                new int[]{java.sql.Types.INTEGER});   
	}


	@Override
	public void save(Person p) {
		// TODO Auto-generated method stub
        jdbcTemplate.update("insert into person(name) values(?)", new Object[]{p.getName()},   
                new int[]{java.sql.Types.VARCHAR});
	}

	@Override
	public void update(Person p) {
		// TODO Auto-generated method stub
		 jdbcTemplate.update("update person set name=? where id=?", new Object[]{p.getName(), p.getId()},   
	                new int[]{java.sql.Types.VARCHAR, java.sql.Types.INTEGER});   

	}
	
	@Override
	public Person getPerson(Integer id) {
		// TODO Auto-generated method stub
		 return (Person)jdbcTemplate.queryForObject("select * from person where id=?", new Object[]{id},    
	                new int[]{java.sql.Types.INTEGER}, new PersonRowMapper());   

	}

	@Override
	public List<Person> getPersons() {
		return (List<Person>)jdbcTemplate.query("select * from person", new PersonRowMapper());   

	}

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

import org.springframework.jdbc.core.RowMapper;


public class PersonRowMapper implements RowMapper {

	/**
	 * 上面得事先用了一个PersonRowMapper,我们先看看PersonRowMapper类,
	 * 它实现了RowMapper接口,这是spring中的一个接口,
	 * 一般在查找方法中使用,目的是为了帮我们把结果集中的数据封装成对象
     * RowMapper可以将数据中的每一行封装成用户定义的类,在数据库查询中,
     * 如果返回的类型是用户自定义的类型则需要包装,如果是Java自定义的类型,
     * 如:String则不需要,Spring最新的类SimpleJdbcTemplate使用更加简单了。
	 */
	public Object mapRow(ResultSet rs, int index) throws SQLException {
		Person person = new Person(rs.getString("name"));   
        person.setId(rs.getInt("id"));   
        return person; 
	}

}

5.Junit测试

package junit.test;

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

public class JdbcTest {

	private static IPersonService ps;
	
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		try {
			ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
			ps=(IPersonService) ctx.getBean("personService");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	
	public void testSave()   
    {   
           
       for(int i=0; i<5; i++)   
           ps.save(new Person("传智播客"+ i));   
   }   
    
	
    public void testGetPerson(){   
       Person person = ps.getPerson(1);   
       System.out.println(person.getName());   
   }   
     
    
    public void testUpdate(){   
       Person person = ps.getPerson(1);   
       person.setName("张xx");   
       ps.update(person);   
   }   
    
    
    public void testDelete(){   
       ps.delete(1);   
   }   
   
    @Test
   public void testGetBeans(){   
       for(Person person : ps.getPersons()){   
           System.out.println(person.getName());   
       }   
   }   

}
注意,在业务bean里面,如果没有添加@Transactional注解,则没有使用spring的事务管理,每个jdbcTemplate的方法
都自己开启一个事物,若注解了,则每个业务bean的方法为一个事物。
以上的测试比如根据id删除person对象等操作都没有事务,比如我们有一个操作

public void delete(Integer personid) {   
        jdbcTemplate.update("delete from person where id=?", new Object[]{personid},   
                new int[]{java.sql.Types.INTEGER});   
           
        jdbcTemplate.update("delete from person1 where id=?", new Object[]{personid},   
                new int[]{java.sql.Types.INTEGER});   
    }  

public void delete(Integer personid) {
		jdbcTemplate.update("delete from person where id=?", new Object[]{personid},
				new int[]{java.sql.Types.INTEGER});
		
		jdbcTemplate.update("delete from person1 where id=?", new Object[]{personid},
				new int[]{java.sql.Types.INTEGER});
	} 

在第二个操作中,我们把表名字写错误了,写成了person1 ,由于这两个操作没有配置事务,他们都在各自的事务中进行,因此执行:
public void testDelete(){   
        personService.delete(3);   
    }  

public void testDelete(){
		personService.delete(3);
	} 
我们会发现数据库中id为3的那条记录不见了,我们的业务是两个都成功或者失败,现在的结果是一个成功,一个失败,不能满足,
因此我们要把事务加进来。。
 

6.增加属性配置文件

有些同学喜欢讲beans.xml中的数据库德用户名,密码啥的放在一个属性文件中,spring也支持占位符,
可以从一个属性文件中读取配置文件信息,而不需要我们在写读取属性文件的类,只需要配置一下

步骤:

1.首先编写属性配置文件 jdbc.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/test?useUnicode\=true&characterEncoding\=UTF-8
username=root
password=12345678
initialSize=1
maxActive=500
maxIdle=2
minIdle=1


2.编写beans.xml,注意加上    <context:property-placeholder location="classpath:jdbc.properties"/>

<?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:aop="http://www.springframework.org/schema/aop"  
       xmlns:context="http://www.springframework.org/schema/context"  
       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/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   
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">  
  
     
  <aop:aspectj-autoproxy proxy-target-class="true"/>  
  <!-- 配置数据源 -->  
   <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}"/>  
         <!-- 连接池启动时的初始值 -->  
         <property name="initialSize" value="${initialSize}"/>  
         <!-- 连接池的最大值 -->  
         <property name="maxActive" value="${maxActive}"/>  
         <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->  
         <property name="maxIdle" value="${maxIdle}"/>  
         <!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->  
         <property name="minIdle" value="${minIdle}"/>  
  </bean>  
  <!-- 配置事务-->  
 <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
    <property name="dataSource" ref="dataSource"/>  
  </bean>  
  <!-- 配置事务管理器 -->  
  <tx:annotation-driven transaction-manager="txManager"/>  
   <bean id="personService" class="cn.com.xinli.service.impl.PersonServiceBean">  
    <property name="dataSource" ref="dataSource"></property>  
   </bean>  
</beans>  
 

抱歉!评论已关闭.