使用Spring+JDBC组合步骤如下:
一、首先:配置数据源如:
在配置数据源时,先添加spring开发能力,添加库文件{
Spring 2.5 AOP Libraries
Spring 2.5 Core Libraries
Spring 2.5 Persistence Core Libraries
Spring 2.5 Persistence JDBC Libraries //这个可不要忘了加
}
注意: ${}是把dataSource的属性放到properties文档里面
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="${driverClassName}">
</property>
<property name="url"
value="${url}">
</property>
<property name="username" value="${username}"></property>
<property name="password" value="${password}"></property>
<!-- 连接池启动时的初始值 -->
<property name="initialSize" value="${initialSize}"></property>
<!-- 连接池的最大值 -->
<property name="maxActive" value="${maxActive}"></property>
<!-- 最大空间值、当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,直至减少的maxIdle为止 -->
<property name="maxIdle" value="${maxIdle}"></property>
<!-- 最小空间值,当空间的连接数少于阀值时,连接池就会预申请一些连接,以免洪峰来时 来不及申请 -->
<property name="minIdle" value="${minIdle}"></property>
</bean>
可以把配置放到属性文件里面去 jdbc.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/test?useUnicode\=true&characterEncoding\=UTF-8
username=root
password=fly
initialSize=1
maxActive=500
maxIdle=2
minIdle=1
在spring容器中加入下面代码
<context:property-placeholder location="classpath:jdbc.properties"/>
二、配置事务,配置事务时,需要在xml配置文件中引入用于声明事务的tx命名空间,
事务的配置有两种:注解方式和基于XML配置方式
在这里我采用“注解方式”如: <bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
abstract="false" lazy-init="default"
dependency-check="default">
<property name="dataSource"> //要求注入数据源,dataSource是我们自己定义的数据源
<ref bean="dataSource" />
</property>
</bean>
我们采用注解方式,
<!-- 采用@Transaction注解方式使用事务 -->
<tx:annotation-driven transaction-manager="txManager"/> //transaction-manager属性指定事务管理器
首先添加tx:的命名空间:红色的是tx的命名空间
<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">
</beans>
经过这几步的配置,我们已经配置好了spring到jdbc的集成
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: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">
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="${driverClassName}">
</property>
<property name="url"
value="${url}">
</property>
<property name="username" value="${username}"></property>
<property name="password" value="${password}"></property>
<!-- 连接池启动时的初始值 -->
<property name="initialSize" value="${initialSize}"></property>
<!-- 连接池的最大值 -->
<property name="maxActive" value="${maxActive}"></property>
<!-- 最大空间值、当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,直至减少的maxIdle为止 -->
<property name="maxIdle" value="${maxIdle}"></property>
<!-- 最小空间值,当空间的连接数少于阀值时,连接池就会预申请一些连接,以免洪峰来时 来不及申请 -->
<property name="minIdle" value="${minIdle}"></property>
</bean>
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
abstract="false" lazy-init="default"
dependency-check="default">
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
<bean id="personService" class="com.xt.service.impl.PersonServiceBean">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
三、接下来,建表,编写业务逻辑,增删查改
建表:表名:person
字段:id Intege primary key autoincrment 自增
字段:name varchar(20)
首先:定义接口:PersionService
package com.xt.service;
import java.util.List;
import com.xt.bean.Person;
public interface PersonService {
public void save(Person person);
public void update(Person person);
public Person getPerson(Integer personid);
public List<Person> getPersons();
public void delete(Integer personid);
}
建立bean类 :Person
package com.xt.bean;
public class Person {
public Integer id;
public String name;
public Person(){};
public Person(String name) {
this.name=name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
给PersonService接口,创建实现类PersonServiceBean
package com.xt.service.impl;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;
import com.xt.bean.Person;
import com.xt.service.PersonService;
@Transactional
public class PersonServiceBean implements PersonService {
private JdbcTemplate jdbcTemplate; //我们使用spring提供的JdbcTemplate类进行管理,
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Transactional(rollbackFor=Exception.class)
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 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()},
new int[]{java.sql.Types.VARCHAR,java.sql.Types.INTEGER});
}
}
还需要一个回调接口PersonRowMapper
package com.xt.service.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;
import com.xt.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;
}
}
把PersonServiceBean交给spring,把下面的代码加到spring容器管理
<bean id="personService" class="com.xt.service.impl.PersonServiceBean">
<property name="dataSource" ref="dataSource" /> //获取数据源
</bean>
然后,我们来进行测试建立一个单元测试
package junit.test;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.xt.bean.Person;
import com.xt.service.PersonService;
public class PersonServiceBeanTest {
private static PersonService personService;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
ApplicationContext cxt = new ClassPathXmlApplicationContext(
"/applicationContext.xml");
personService = (PersonService) cxt.getBean("personService");
}
@Test
public void save() {
for (int i = 0; i < 5; i++) {
personService.save(new Person("众志成城" + i));
}
}
@Test
public void update() {
Person person = personService.getPerson(1);
person.setName("我是大好人");
System.out.println(person.getName());
}
@Test
public void getPerson() {
Person person = personService.getPerson(1);
System.out.println(person.getName());
}
@Test
public void delete() {
personService.delete(2);
}
@Test
public void getBeans() {
for (Person p : personService.getPersons())
System.out.println(p.getId() + " = " + p.getName());
}
}