深入探索spring技术内幕(八): Spring +JDBC组合开发和事务控制

来源:互联网 发布:去南极旅游知乎 编辑:程序博客网 时间:2024/05/17 03:24

一. 配置数据源

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
  2.    <property name="driverClassName" value="org.gjt.mm.mysql.Driver"/>  
  3.    <property name="url" value="jdbc:mysql://localhost:3306/itcast?useUnicode=true&characterEncoding=UTF-8"/>  
  4.    <property name="username" value="root"/>  
  5.    <property name="password" value="123456"/>  
  6.    <!-- 连接池启动时的初始值 -->  
  7.    <property name="initialSize" value="1"/>  
  8.    <!-- 连接池的最大值 -->  
  9.    <property name="maxActive" value="500"/>  
  10.    <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->  
  11.    <property name="maxIdle" value="2"/>  
  12.    <!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->  
  13.    <property name="minIdle" value="1"/>  
  14.  </bean>  


使用<context:property-placeholderlocation=“jdbc.properties”/>属性占位符

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <context:property-placeholder location=“jdbc.properties”/>   
  2.  <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">  
  3.     <property name="driverClassName" value="${driverClassName}"/>  
  4.     <property name="url" value="${url}"/>  
  5.     <property name="username" value="${username}"/>  
  6.     <property name="password" value="${password}"/>  
  7.     <!-- 连接池启动时的初始值 -->  
  8.     <property name="initialSize" value="${initialSize}"/>  
  9.     <!-- 连接池的最大值 -->  
  10.     <property name="maxActive" value="${maxActive}"/>  
  11.     <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->  
  12.     <property name="maxIdle" value="${maxIdle}"/>  
  13.     <!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来不及申请 -->  
  14.     <property name="minIdle" value="${minIdle}"/>  
  15.  </bean>  
jdbc.properties

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. driverClassName=org.gjt.mm.mysql.Driver  
  2. url=jdbc\:mysql\://localhost\:3306/itcast?useUnicode\=true&characterEncoding\=UTF-8  
  3. username=root  
  4. password=123456  
  5. initialSize=1  
  6. maxActive=500  
  7. maxIdle=2  
  8. minIdle=1  


二. 配置事务

[ 注解配置 ]

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  2.     <property name="dataSource" ref="dataSource"/>  
  3. </bean>  
  4. <!– 采用@Transactional注解方式使用事务  -->  
  5. <tx:annotation-driven transaction-manager="txManager"/>  
  6.   
  7. @Service @Transactional  
  8. public class PersonServiceBean implements PersonService {  
  9. }  

[ XML配置 ]

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  2.     <property name="dataSource" ref="dataSource"/>  
  3. </bean>  
  4. <aop:config>  
  5.     <aop:pointcut id="transactionPointcut" expression="execution(* com.zdp.service..*.*(..))"/>  
  6.     <aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/>  
  7. </aop:config>   
  8. <tx:advice id="txAdvice" transaction-manager="txManager">  
  9.     <tx:attributes>  
  10.         <tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/>  <!-- 查询不用设置事务-->  
  11.         <tx:method name="*"/>  
  12.     </tx:attributes>  
  13. </tx:advice>  


三. 事务传播属性

所谓事务传播属性是指多个事务方法调用时,事务如何在这些方法间传播

REQUIRED:业务方法需要在一个事务中运行。如果方法运行时,已经处在一个事务中,那么加入到该事务,否则为自己创建一个新的事务。
这是Spring默认的事务传播行为!!


NOT_SUPPORTED:声明方法不需要事务。如果方法没有关联到一个事务,容器不会为它开启事务。如果方法在一个事务中被调用,该事务会被挂起,在方法调用结束后,原先的事务便会恢复执行。


REQUIRESNEW:属性表明不管是否存在事务,业务方法总会为自己发起一个新的事务。如果方法已经运行在一个事务中,则原有事务会被挂起,新的事务会被创建,直到方法执行结束,新事务才算结束,原先的事务才会恢复执行。


MANDATORY:该属性指定业务方法只能在一个已经存在的事务中执行,业务方法不能发起自己的事务。如果业务方法在没有事务的环境下调用,容器就会抛出例外。

SUPPORTS:这一事务属性表明,如果业务方法在某个事务范围内被调用,则方法成为该事务的一部分。如果业务方法在事务范围外被调用,则方法在没有事务的环境下执行。


Never:指定业务方法绝对不能在事务范围内执行。如果业务方法在某个事务中执行,容器会抛出例外,只有业务方法没有关联到任何事务,才能正常执行。


NESTED:如果一个活动的事务存在,则运行在一个嵌套的事务中. 如果没有活动事务, 则按REQUIRED属性执行.它使用了一个单独的事务,这个事务拥有多个可以回滚的保存点。内部事务的回滚不会对外部事务造成影响。它只对DataSourceTransactionManager事务管理器起效


四. 使用JdbcTemplate

1. 一个实际的例子:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class PersonServiceImpl implements PersonService {  
  2.     private JdbcTemplate jdbcTemplate;  
  3.   
  4.     public void setDataSource(DataSource dataSource) {  
  5.         this.jdbcTemplate = new JdbcTemplate(dataSource);  
  6.     }  
  7.   
  8.     // 删除一条用户记录  
  9.     public void delete(Integer personid) throws Exception {  
  10.         jdbcTemplate.update("delete from person where id=?",   
  11.                             new Object[] { personid },   
  12.                             new int[] { java.sql.Types.INTEGER });  
  13.     }  
  14.     
  15.     // 查询一条用户记录  
  16.     public Person getPerson(Integer personid) {  
  17.         return (Person) jdbcTemplate.queryForObject("select * from person where id=?",   
  18.                 new Object[] { personid },  
  19.                 new int[] { java.sql.Types.INTEGER }, new PersonRowMapper() {  
  20.                     public Object mapRow(ResultSet rs, int index) throws SQLException {  
  21.                         Person person = new Person(rs.getString("name"));  
  22.                         person.setId(rs.getInt("id"));  
  23.                         return person;  
  24.                     }  
  25.                 });  
  26.     }  
  27.   
  28.     // 查询多条用户记录  
  29.     @SuppressWarnings("unchecked")  
  30.     public List<Person> getPersons() {  
  31.         return (List<Person>) jdbcTemplate.query("select * from person",   
  32.             new PersonRowMapper() {  
  33.                 public Object mapRow(ResultSet rs, int index) throws SQLException {  
  34.                     Person person = new Person(rs.getString("name"));  
  35.                     person.setId(rs.getInt("id"));  
  36.                     return person;  
  37.                 }  
  38.             });  
  39.     }  
  40.   
  41.     // 插入一条用户记录  
  42.     public void save(Person person) {  
  43.         jdbcTemplate.update("insert into person(name) values(?)",   
  44.                              new Object[] { person.getName() },   
  45.                              new int[] { java.sql.Types.VARCHAR });  
  46.     }  
  47.   
  48.     // 更新一条用户记录  
  49.     public void update(Person person) {  
  50.         jdbcTemplate.update("update person set name=? where id=?",   
  51.                             new Object[] { person.getName(), person.getId() },   
  52.                             new int[] {java.sql.Types.VARCHAR, java.sql.Types.INTEGER });  
  53.     }  
  54. }  

五. 事务解惑

1. 事务方法嵌套调用

spring默认的事务传播行为是REQUIRED,如果当前没有事务,就新建一个事务,如果已经存在一个事务中,就加入到这个事务中。


2. 多线程问题

sping的bean都是单实例的,一个类能够以单实例的方式运行的前提是无状态,即一个类不能拥有状态化的成员变量。在传统的编程中,dao必须持有一个connection,而connection即是状态化的对象,所以传统的dao不能做成单实例的,每次要用时必须new一个新的实例,传统 的service由于将有状态的dao作为成员变量,所以传统的service本身也是有状态的。

但是在spring中,dao和service都以单实例的方式存在,spring是通过ThreadLocal将有状态的变量(如Connection)本地线程化,达到另一个层面上的线程无关,从而达到线程安全。spring不遗余力地将状态化的对象无状态化,就是要达到单实例化bean的目的。

由于spring已经通过ThreadLocal的设施将Bean无状态化,所以spring中单实例bean对线程安全问题用于了一种天生的免疫能力。


3. 不能被spring aop事务增强的方法:


不能被spring事务增强的特殊方法并非就不工作在事务环境下,只要它们被外层的事务方法调用了,用于spring的事务管理的传播特殊,内部方法也可以工作在外部方法所启动的事务上下文中。


4. 数据连接(connection)泄露问题 

使用JdbcTemplate, HibernateTemplate进行数据访问,一定不会存在连接泄露的问题。

来看一下 JdbcTemplate 最核心的一个数据操作方法 execute():

public <T> T execute(StatementCallback<T> action) throws DataAccessException {    //① 首先根据DataSourceUtils获取数据连接    Connection con = DataSourceUtils.getConnection(getDataSource());    Statement stmt = null;    try {        Connection conToUse = con;        …        handleWarnings(stmt);        return result;    }    catch (SQLException ex) {        JdbcUtils.closeStatement(stmt);        stmt = null;        DataSourceUtils.releaseConnection(con, getDataSource());        con = null;        throw getExceptionTranslator().translate(            "StatementCallback", getSql(action), ex);    }    finally {        JdbcUtils.closeStatement(stmt);        //② 最后根据DataSourceUtils释放数据连接        DataSourceUtils.releaseConnection(con, getDataSource());    }}

但是如果我们直接获取数据连接,使用不当就可能会造成连接泄露的问题

// ①直接从数据源获取连接,后续程序没有显式释放该连接Connection conn = jdbcTemplate.getDataSource().getConnection(); String sql = "UPDATE t_user SET last_logon_time=? WHERE user_name =?";
0 0
原创粉丝点击