<bean id="dataSource" class="org.apache.dbcp.BasicDataSource" destroy-method="close"><property name="driverClassName" value="org.gjt.mm.mysql.Driver" /><property name="url" value="jdbc:mysql://localhost:3306/itcast?useUnicode=true&characterEncoding=UTF-8" /><property name="username" value="root" /><property name="password" value="123456" /><!-- ........略 --></bean>
配置事务时,需要在xml配置文件中引入用于声明食物的tx命名空间(见下页),事务的配置方式有两种:注解方式和基于XML配置方式。
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/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
/*
Navicat MySQL Data TransferSource Server : localhost
Source Server Version : 50133
Source Host : localhost:3306
Source Database : itcastTarget Server Type : MYSQL
Target Server Version : 50133
File Encoding : 65001Date: 2010-07-23 15:54:58
*/SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `person`
-- ----------------------------
DROP TABLE IF EXISTS `person`;
CREATE TABLE `person` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ----------------------------
-- Records of person
-- ----------------------------
<?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/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 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/itcast?useUnicode=true&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>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 采用@Transactional注解方式使用事务 -->
<tx:annotation-driven transaction-manager="txManager" />
<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean" >
<property name="dataSource" ref="dataSource"></property>
</bean></beans>
package cn.itcast.bean;/**
*
* @author kang.cunhua
*/
public class Person {private Integer id;
private String name;public Person() {
}public Person(Integer id, String name) {
this.id = id;
this.name = name;
}/**
* @return the id
*/
public Integer getId() {
return id;
}/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}/**
* @return the name
*/
public String getName() {
return name;
}/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
}
package cn.itcast.service;import cn.itcast.bean.Person;
import java.util.List;/**
*
* @author kang.cunhua
*/
public interface PersonService {/**
* 保存person
* @param person
*/
public void save(Person person);/**
* 更新person
* @param person
*/
public void update(Person person);/**
* 获取person
* @param personid
* @return
*/
public String getPerson(Integer personid);
/**
* 获取所有person
* @return
*/
public List<Person> getPersons();
/**
* 删除指定id的person
* @param personid
*/
public void delete (Integer personid);
}
package cn.itcast.service.impl;import cn.itcast.bean.Person;
import cn.itcast.service.PersonService;
import java.util.List;
import javax.sql.DataSource;/**
*
* @author kang.cunhua
*/
public class PersonServiceBean implements PersonService {
private DataSource dataSource;@Override
public void save(Person person) {
System.out.println("俺是save(Person person)方法!");}@Override
public void update(Person person) {
System.out.println("俺是update(Person person)方法!");}@Override
public String getPerson(Integer personid) {
System.out.println("俺是getPerson(Integer personid)方法!");
return null;
}@Override
public List<Person> getPersons() {
System.out.println("俺是getPersons()方法!");
return null;
}@Override
public void delete(Integer personid) {
System.out.println("俺是delete(Integer personid)方法!");
}/**
* @param dataSource the dataSource to set
*/
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}}
package cn.itcast.service.impl;import cn.itcast.service.PersonService;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;/**
*
* @author kang.cunhua
*/
public class PersonServiceBeanTest {
private static PersonService personService;public PersonServiceBeanTest() {
}@BeforeClass
public static void setUpClass() throws Exception {
ApplicationContext cxt = new ClassPathXmlApplicationContext("beans.xml");
personService = (PersonService) cxt.getBean("personService");
}@AfterClass
public static void tearDownClass() throws Exception {
}@Before
public void setUp() {
}/**
* Test of save method, of class PersonServiceBean.
*/
@Test
public void testSave() {personService.save(null);}/**
* Test of update method, of class PersonServiceBean.
*/
@Test
public void testUpdate() {
personService.update(null);
}/**
* Test of getPerson method, of class PersonServiceBean.
*/
@Test
public void testGetPerson() {
personService.getPerson(1);
}/**
* Test of getPersons method, of class PersonServiceBean.
*/
@Test
public void testGetPersons() {
personService.getPersons();
}/**
* Test of delete method, of class PersonServiceBean.
*/
@Test
public void testDelete() {
personService.delete(1);
}/**
* Test of setDataSource method, of class PersonServiceBean.
*/
@Test
public void testSetDataSource() {
}
}
2010-7-23 16:03:10 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@fa7e74: display name [org.springframework.context.support.ClassPathXmlApplicationContext@fa7e74]; startup date [Fri Jul 23 16:03:10 CST 2010]; root of context hierarchy
2010-7-23 16:03:10 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans.xml]
2010-7-23 16:03:10 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
信息: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@fa7e74]: org.springframework.beans.factory.support.DefaultListableBeanFactory@4cee32
2010-7-23 16:03:10 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@4cee32: defining beans [dataSource,txManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,personService]; root of factory hierarchy
俺是save(Person person)方法!
俺是update(Person person)方法!
俺是getPerson(Integer personid)方法!
俺是getPersons()方法!
俺是delete(Integer personid)方法!
/*
Navicat MySQL Data TransferSource Server : localhost
Source Server Version : 50133
Source Host : localhost:3306
Source Database : itcastTarget Server Type : MYSQL
Target Server Version : 50133
File Encoding : 65001Date: 2010-07-23 15:54:58
*/SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `person`
-- ----------------------------
DROP TABLE IF EXISTS `person`;
CREATE TABLE `person` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;-- ----------------------------
-- Records of person
-- ----------------------------
<?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/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 id="dataSource" destroy-method="close">
<property name="driverClassName" value="org.gjt.mm.mysql.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/itcast?useUnicode=true&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>
<bean id="txManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 采用@Transactional注解方式使用事务 -->
<tx:annotation-driven transaction-manager="txManager" />
<bean id="jdbcUtils" >
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="personDao" >
<property name="jdbcUtils" ref="jdbcUtils"></property>
</bean>
<bean id="personService" >
<property name="personDao" ref="personDao"></property>
</bean></beans>
Person.java
package cn.itcast.bean;
/**
*
* @author kang.cunhua
*/
public class Person {private Integer id;
private String name;public Person() {
}public Person(Integer id, String name) {
this.id = id;
this.name = name;
}/**
* @return the id
*/
public Integer getId() {
return id;
}/**
* @param id the id to set
*/
public void setId(Integer id) {
this.id = id;
}/**
* @return the name
*/
public String getName() {
return name;
}/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
}
PersonDao.java
package cn.itcast.dao;
import cn.itcast.bean.Person;
import java.util.List;/**
*
* @author kang.cunhua
*/
public interface PersonDao {
/**
* 保存person
* @param person
*/
public void save(Person person);/**
* 更新person
* @param person
*/
public void update(Person person);/**
* 获取person
* @param personid
* @return
*/
public String getPerson(Integer personid);
/**
* 获取所有person
* @return
*/
public List<Person> getPersons();
/**
* 删除指定id的person
* @param personid
*/
public void delete (Integer personid);}
PersonDaoBean.java
package cn.itcast.dao.impl;
import cn.itcast.bean.Person;
import cn.itcast.dao.PersonDao;
import cn.itcast.utils.JdbcUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;/**
*
* @author kang.cunhua
*/
public class PersonDaoBean implements PersonDao {private JdbcUtils jdbcUtils;
@Override
public void save(Person person) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "insert into person(name) values (?) ";
try {
conn = jdbcUtils.getConnection();
ps = conn.prepareStatement(sql);
ps.setString(1, person.getName());
ps.execute();} catch (SQLException ex) {
Logger.getLogger(PersonDaoBean.class.getName()).log(Level.SEVERE, null, ex);
} finally {
JdbcUtils.free(rs, ps, conn);
}
System.out.println("俺是save(Person person)方法!");
}@Override
public void update(Person person) {
System.out.println("俺是update(Person person)方法!");
}@Override
public String getPerson(Integer personid) {
System.out.println("俺是getPerson(Integer personid)方法!");
return null;
}@Override
public List<Person> getPersons() {
System.out.println("俺是getPersons()方法!");
return null;
}@Override
public void delete(Integer personid) {
System.out.println("俺是getPersons()方法!");
}/**
* @param jdbcUtils the jdbcUtils to set
*/
public void setJdbcUtils(JdbcUtils jdbcUtils) {
this.jdbcUtils = jdbcUtils;
}
}
PersonService.java
package cn.itcast.service;
import cn.itcast.bean.Person;
import java.util.List;/**
*
* @author kang.cunhua
*/
public interface PersonService {
public void regist(Person person);
public List retrieve();
}
PersonServiceBean.java
package cn.itcast.service.impl;
import cn.itcast.bean.Person;
import cn.itcast.service.PersonService;
import cn.itcast.dao.PersonDao;
import java.util.List;/**
*
* @author kang.cunhua
*/
public class PersonServiceBean implements PersonService {private PersonDao personDao;
@Override
public void regist(Person person) {
personDao.save(person);
}@Override
public List retrieve() {
return personDao.getPersons();}
/**
* @param personDao the personDao to set
*/
public void setPersonDao(PersonDao personDao) {
this.personDao = personDao;
}
}
JdbcUtil.java
package cn.itcast.utils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.DataSource;/**
*
* @author kang.cunhua
*/
public class JdbcUtils {private DataSource dataSource;
public Connection getConnection() throws SQLException {
return dataSource.getConnection();
}/**
* @param dataSource the dataSource to set
*/
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}public static void free(ResultSet rs, Statement st, Connection conn) {
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null) {
st.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
// myDataSource.free(conn);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
单元测试:PersonServiceBeanTest.java
package cn.itcast.service.impl;
import cn.itcast.bean.Person;
import cn.itcast.service.PersonService;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;/**
*
* @author kang.cunhua
*/
public class PersonServiceBeanTest {private static PersonService personService;
public PersonServiceBeanTest() {
}@BeforeClass
public static void setUpClass() throws Exception {
ApplicationContext cxt = new ClassPathXmlApplicationContext("beans.xml");
personService = (PersonService) cxt.getBean("personService");
}@AfterClass
public static void tearDownClass() throws Exception {
}@Before
public void setUp() {
}/**
* Test of save method, of class PersonServiceBean.
*/
@Test
public void testSave() {
Person person = new Person();
person.setName("郭德纲");
personService.regist(person);
}/**
* Test of update method, of class PersonServiceBean.
*/
@Test
public void testRetrievee() {
personService.retrieve();
}
}
本文到目前为止还暂无回复