七
26
22_传智播客Spring2.5视频教程_Spring集成的jdbc编码和事务管理
使用Spring的JdbcTemplate完善JDBC数据库CRUD
private JdbcTemplate jdbcTemplate;
/**
* @param dataSource the dataSource to set
*/
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}…………..@Override
public void save(Person person) {
System.out.println(“俺是save(Person person)方法!”);
jdbcTemplate.update(“insert into person(name) values(?)”,
new Object[]{person.getName()},
new int[]{java.sql.Types.VARCHAR});}
……………..@Override
public Person getPerson(Integer personid) {
System.out.println(“俺是getPerson(Integer personid)方法!”);
return (Person) jdbcTemplate.queryForObject(“select * from person where id=?”, new Object[]{personid},
new int[]{java.sql.Types.INTEGER},
new PersonRowMapper());
}
getPerson(Integer personid)使用到RowMapper接口
public class PersonRowMapper implements RowMapper {@Override
public Object mapRow(ResultSet rs, int i) throws SQLException {
Person person = new Person(rs.getString(“name”));
person.setId(rs.getInt(“id”));
return person;
}}
spring提供的事务注解
如果不是用spring提供的事务注解,默认情况下,业务bean中的方法每条sql都是在各自独立的事务中执行的;
使用@Transactional的话,在调用方法业务bean中方法前会打开事务,在调用后会关闭事务。确保业务bean中方法内部是在一个事务中执行的;// 这些设定在实际开发中 会很有用的。
保留表结构,清楚所有数据:
TRUNCATE TABLE person
上代码:
上代码:
beans.xml
<?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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd”>
<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>
<!– 采用@Transactional注解方式使用事务 –>
<tx:annotation-driven transaction-manager=”txManager” />
<bean id=”personService” class=”cn.itcast.service.impl.PersonServiceBean” >
<property name=”dataSource” ref=”dataSource”></property>
</bean></beans>
jdbc.properties
# To change this template, choose Tools | Templates
# and open the template in the editor.
driverClassName =org.gjt.mm.mysql.Driver
url=jdbc:mysql://localhost:3306/itcast?useUnicode=true&characterEncoding=UTF-8
username=root
password=
initialSize =1
maxActive=500
maxIdle=2
minIdle=1
Person.java
package cn.itcast.bean;/**
*
* @author kang.cunhua
*/
public class Person {private Integer id;
private String name;public Person() {
}public Person(String name) {this.name = name;
}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;
}
}
PersonService.java
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 Person getPerson(Integer personid);
/**
* 获取所有person
* @return
*/
public List<Person> getPersons();
/**
* 删除指定id的person
* @param personid
*/
public void delete (Integer personid);
}
PersonRowMapper.java
package cn.itcast.service.impl;import cn.itcast.bean.Person;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;/**
*
* @author kang.cunhua
*/
public class PersonRowMapper implements RowMapper {@Override
public Object mapRow(ResultSet rs, int i) throws SQLException {
Person person = new Person(rs.getString(“name”));
person.setId(rs.getInt(“id”));
return person;
}}
PersonServiceBean.java
package cn.itcast.service.impl;import cn.itcast.bean.Person;
import cn.itcast.service.PersonService;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Transactional;/**
*
* @author kang.cunhua
*/
@Transactional
public class PersonServiceBean implements PersonService {private JdbcTemplate jdbcTemplate;@Override
public void save(Person person) {
System.out.println(“俺是save(Person person)方法!”);
jdbcTemplate.update(“insert into person(name) values(?)”,
new Object[]{person.getName()},
new int[]{java.sql.Types.VARCHAR});}@Override
public void update(Person person) {
System.out.println(“俺是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});}@Override
public Person getPerson(Integer personid) {
System.out.println(“俺是getPerson(Integer personid)方法!”);
return (Person) jdbcTemplate.queryForObject(“select * from person where id=?”, new Object[]{personid},
new int[]{java.sql.Types.INTEGER},
new PersonRowMapper());
}@Override
public List<Person> getPersons() {
System.out.println(“俺是getPersons()方法!”);
return (List<Person>) jdbcTemplate.query(“select * from person”, new PersonRowMapper());
}@Override
public void delete(Integer personid) {
System.out.println(“俺是delete(Integer personid)方法!”);
jdbcTemplate.update(“delete from person where id=?”,
new Object[]{personid},
new int[]{java.sql.Types.INTEGER});
}/**
* @param dataSource the dataSource to set
*/
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
}
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() {
for (int i = 0; i < 5; i++) {
personService.save(new Person(“传智播客” + i));
}}/**
* Test of getPerson method, of class PersonServiceBean.
*/
@Test
public void testGetPerson() {
Person person = personService.getPerson(2);
System.out.println(” testGetPerson() :” + person.getName());
}/**
* Test of update method, of class PersonServiceBean.
*/
@Test
public void testUpdate() {
Person person = personService.getPerson(2);
person.setName(“张**”);
personService.update(person);}/**
* Test of getPersons method, of class PersonServiceBean.
*/
@Test
public void testGetPersons() {
for (Person person:personService.getPersons()) {
System.out.println(“testGetPersons():” + person.getName());
}
}/**
* Test of delete method, of class PersonServiceBean.
*/
@Test
public void testDelete() {
personService.delete(1);
}
}
输出:
2010-7-26 14:17:32 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1decdec: display name [org.springframework.context.support.ClassPathXmlApplicationContext@1decdec]; startup date [Mon Jul 26 14:17:32 CST 2010]; root of context hierarchy
2010-7-26 14:17:32 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from class path resource [beans.xml]
2010-7-26 14:17:33 org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
信息: Bean factory for application context [org.springframework.context.support.ClassPathXmlApplicationContext@1decdec]: org.springframework.beans.factory.support.DefaultListableBeanFactory@193722c
2010-7-26 14:17:33 org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
信息: Loading properties file from class path resource [jdbc.properties]
2010-7-26 14:17:33 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
信息: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@193722c: defining beans [org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,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)方法!
俺是save(Person person)方法!
俺是save(Person person)方法!
俺是save(Person person)方法!
俺是save(Person person)方法!
俺是getPerson(Integer personid)方法!
testGetPerson() :传智播客1
俺是getPerson(Integer personid)方法!
俺是update(Person person)方法!
俺是getPersons()方法!
testGetPersons():传智播客0
testGetPersons():张**
testGetPersons():传智播客2
testGetPersons():传智播客3
testGetPersons():传智播客4
俺是delete(Integer personid)方法!
视频给出的代码并没有DAO层,直接在service层进行了一些DAO层的操作。个人觉得还是独立出来dao层比较好。维护和扩展方便。可以参考俺上一讲的笔记后边作出的改进。
本文到目前为止还暂无回复