Spring+JDBC组合开发配置数据源有两种方式:
1.基于XML
2.基于注解
首先我们看看基于XML的配置:
步骤:
1.首先导入我们数据源依赖的jar包,如下图
2.写beans.xml配置文件,配置事务时,需要在xml配置文件中引入用于声明事务的tx命名空间
比以前的配置文件多了
xmlns:tx="http://www.springframework.org/schema/tx"
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
<?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"/>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="root"/>
<property name="password" value="12345678"/>
<!-- 连接池启动时的初始值 -->
<property name="initialSize" value="1"/>
<!-- 连接池的最大值 -->
<property name="maxActive" value="500"/>
<!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->
<property name="maxIdle" value="2"/>
<!-- 最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->
<property name="minIdle" value="1"/>
</bean>
<!-- 配置事务-->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置事务管理器 -->
<tx:annotation-driven transaction-manager="txManager"/>
3.建立数据库和表,这里用的是mysql,建立一个test数据库,下面整一个表person,表结构比较简单,只有一个Id和name字段,id自动增长。
4.面向接口编程,开始写接口和实现,目的是实现对person表的增删改查操作
先写接口 :PersonService.java
package cn.com.xinli.service;
import java.util.List;
import cn.com.xinli.bean.Person;
public interface PersonService
{
/**
* ����person
* @param person
*/
public void save(Person person);
/**
* ����person
* @param person
*/
public void update(Person person);
/**
* ��ȡperson
* @param personid
* @return
*/
public Person getPerson(Integer personid);
/**
* ��ȡ����person
* @return
*/
public List<Person> getPersons();
/**
* ɾ��ָ��id��person
* @param personid
*/
public void delete(Integer personid);
}
在写实现 PersonServiceBean.java
package cn.com.xinli.service.impl;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import cn.com.xinli.bean.Person;
import cn.com.xinli.service.PersonService;
public class PersonServiceBean implements PersonService
{
public JdbcTemplate jdbcTemplate;
public DataSource dataSource;
public DataSource getDataSource()
{
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public void delete(Integer personid) {
jdbcTemplate.update("delete from person where id=?", new Object[]{personid},
new int[]{java.sql.Types.INTEGER});
}
public Person getPerson(Integer personid) {
return (Person)jdbcTemplate.queryForObject("select * from person where id=?", new Object[]{personid},
new int[]{java.sql.Types.INTEGER}, new PersonRowMapper());
}
@SuppressWarnings("unchecked")
public List<Person> getPersons() {
return (List<Person>)jdbcTemplate.query("select * from person", new PersonRowMapper());
}
public void save(Person person) {
jdbcTemplate.update("insert into person(name) values(?)", new Object[]{person.getName()},
new int[]{java.sql.Types.VARCHAR});
}
public void update(Person person) {
jdbcTemplate.update("update person set name=? where id=?", new Object[]{person.getName(), person.getId()},
new int[]{java.sql.Types.VARCHAR, java.sql.Types.INTEGER});
}
}
上面得事先用了一个PersonRowMapper,我们先看看PersonRowMapper类,它实现了RowMapper接口,这是spring中的一个接口,一般在查找方法中使用,目的是为了帮我们把结果集中的数据封装成对象
RowMapper可以将数据中的每一行封装成用户定义的类,在数据库查询中,如果返回的类型是用户自定义的类型则需要包装,如果是Java自定义的类型,如:String则不需要,Spring最新的类SimpleJdbcTemplate使用更加简单了。
package cn.com.xinli.service.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import cn.com.xinli.bean.Person;
public class PersonRowMapper implements RowMapper
{
public Object mapRow(ResultSet rs, int index) throws SQLException
{
Person person = new Person(rs.getString("name"));
person.setId(rs.getInt("id"));
return person;
}
}
5 。测试
package junit.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.com.xinli.bean.Person;
import cn.com.xinli.service.PersonService;
import junit.framework.TestCase;
public class PersonServiceTest extends TestCase
{
private static PersonService personService;
protected void setUp() throws Exception
{
try {
ApplicationContext cxt = new ClassPathXmlApplicationContext("beans.xml");
personService = (PersonService) cxt.getBean("personService");
} catch (RuntimeException e) {
e.printStackTrace();
}
}
public void testSave()
{
for(int i=0; i<5; i++)
personService.save(new Person("传智播客"+ i));
}
public void testGetPerson(){
Person person = personService.getPerson(1);
System.out.println(person.getName());
}
public void testUpdate(){
Person person = personService.getPerson(1);
person.setName("张xx");
personService.update(person);
}
public void testDelete(){
personService.delete(1);
}
public void testGetBeans(){
for(Person person : personService.getPersons()){
System.out.println(person.getName());
}
}
}
结果:略
以上的测试比如根据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});
}
在第二个操作中,我们把表名字写错误了,写成了person1 ,由于这两个操作没有配置事务,他们都在各自的事务中进行,因此执行:
public void testDelete(){
personService.delete(3);
}
我们会发现数据库中id为3的那条记录不见了,我们的业务是两个都成功或者失败,现在的结果是一个成功,一个失败,不能满足,因此我们要把事务加进来。。
使用注解方式加事务特性
只需要在我们的实现类加上下面的注解 @Transactional , 非常方便,在执行测试用例,就会发现已经满足要求了
@Transactional
public class PersonServiceBean implements PersonService
{
}
有些同学喜欢讲beans.xml中的数据库德用户名,密码啥的放在一个属性文件中,spring也支持占位符,可以从一个属性文件中读取配置文件信息,而不需要我们在写读取属性文件的类,只需要配置一下
步骤:
1.首先编写属性配置文件 jdbc.properties
driverClassName=org.gjt.mm.mysql.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>
运行也出现相同的结果