Spring2.5教程:7、Spring+JDBC组合开发和事务

Spring+JDBC组合开发

 使用Spring+JDBC集成步骤如下:

l 配置数据源 , :

 <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&amp;characterEncoding=UTF-8"/>

    <property name="username" value="root"/>

    <property name="password" value="123456"/>

     .....

  </bean>

l 配置事务。配置事务时,需要在 xml 配置文件中引入用于声明事务的 tx 命名空间 ( 见下页 ), 事务的配置方式有两种:注解方式和基于 XML 配置方式。

spring配置文件中引入用于声明事务的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>

配置数据源

 <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&amp;characterEncoding=UTF-8"/>

    <property name="username" value="root"/>

    <property name="password" value="123456"/>

     <!-- 连接池启动时的初始值 -->

   <property name="initialSize" value="1"/>

   <!-- 连接池的最大值 -->

   <property name="maxActive" value="500"/>

   <!-- 最大空闲值.当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接慢慢释放一部分,一直减少到maxIdle为止 -->

   <property name="maxIdle" value="2"/>

   <!--  最小空闲值.当空闲的连接数少于阀值时,连接池就会预申请去一些连接,以免洪峰来时来

不及申请 -->

   <property name="minIdle" value="1"/>

  </bean>

使用属性占位符方式配置数据源

也可以把上述的配置数据源写到.properties文件中,然后使用属性占位符方式加入到spring中,如下所示:

<context:property-placeholderlocation=classpath:jdbc.properties”/>

其中 "classpath: " 表示从classpath的路径下搜索文件为jdbc.properties的文件,然后就可以在Spring的配置文件中这样引用:

<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>

 

采用注解方式配置事务

l 采用注解方式

<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager>

   <!--dataSource对象注入到spring的事务管理类中-->

    <property name="dataSource" ref="dataSource"/>

  </bean>

 <!– 采用@Transactional注解方式使用事务(必须加入tx名字空间)  -->

  <tx:annotation-driven transaction-manager="txManager"/>

配置好后就可以在程序中使用@Transactional来申明事务

@Service @Transactional

public class PersonServiceBean implements PersonService {

}

@Transactional也可以只运行在方法上

 

采用基于XML方式配置事务

<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

    <property name="dataSource" ref="dataSource"/>

</bean>

<aop:config>

    <aop:pointcut id="transactionPointcut" expression="execution(*    

                                                                           cn.itcast.service..*.*(..))"/>

    <aop:advisor advice-ref="txAdvice" pointcut-ref="transactionPointcut"/>

</aop:config>

<tx:advice id="txAdvice" transaction-manager="txManager">

    <tx:attributes> <!--get开始的方法不要事务-->

      <tx:method name="get*" read-only="true" propagation="NOT_SUPPORTED"/>

      <tx:method name="*"/><!--启用默认事务行为,数据库默认级别-->

    </tx:attributes>

</tx:advice>

 

使用JdbcTemplate进行insert/update/delete操作

@Service @Transactional

public class PersonServiceBean implements PersonService {

  private JdbcTemplatejdbcTemplate;

  @Resource

  public void setDataSource(DataSourcedataSource) {

      this.jdbcTemplate = new JdbcTemplate(dataSource);

  }

    //添加

  public void save(Person person) throws Exception{

  jdbcTemplate.update("insert into person (name) values(?)",

  new Object[]{person.getName()}, new int[]{java.sql.Types.VARCHAR});

  }

}

使用JdbcTemplate获取一条记录

@Service @Transactional

public class PersonServiceBean implements PersonService {

  private JdbcTemplatejdbcTemplate;

  @Resource

  public void setDataSource(DataSourcedataSource) {

      this.jdbcTemplate = new JdbcTemplate(dataSource);

  }

   public Person getPerson(Integer id){

  RowMapperrowMapper = new RowMapper(){

  public Object mapRow(ResultSetrs, introwNum) throws SQLException {

  Person person = new Person();

  person.setId(rs.getInt("id"));

  person.setName(rs.getString("name"));

  return person;

  }

  };

  return (Person)jdbcTemplate.queryForObject("select * from person where id=?",

  new Object[]{id}, new int[]{java.sql.Types.INTEGER}, rowMapper);

  }}

使用JdbcTemplate获取多条记录

@Service @Transactional

public class PersonServiceBean implements PersonService {

  private JdbcTemplatejdbcTemplate;

  @Resource

  public void setDataSource(DataSourcedataSource) {

      this.jdbcTemplate = new JdbcTemplate(dataSource);

  }

  public List<Person> getPersons(){

  RowMapperrowMapper = new RowMapper(){

  public Object mapRow(ResultSetrs, introwNum) throws SQLException {

  Person person = new Person();

  person.setId(rs.getInt("id"));

  person.setName(rs.getString("name"));

  return person;

  }

  };

  return jdbcTemplate.query("select * from person", rowMapper);

  }

}

 

事务传播属性

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

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

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

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

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

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

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

spring的事务

spring的事务默认在运行时异常时回滚,在编译异常不回滚,

public void deletePerson(int id) {

  jdbcTemplate.update("delete from person where id=?".......)

  throw new RuntimeExcepton();

  }程序会回滚。

public void deletePerson(int id) throws Exception {

  jdbcTemplate.update("delete from person where id=?".......)

  throw new Excepton();

}不会回滚

要使用发生编译期异常时回滚,可以指定@TransactionalrollbackFor=Excepton.class

@Transactional(rollbackFor=Excepton.classs)

public void deletePerson(int id) throws Exception {

  jdbcTemplate.update("delete from person where id=?".......)

  throw new Excepton();

}

要指定spring的事务传播属性,可以设置 Transactional(propagation=Propagation.XXX)

其中XXX表示上页的事务传播属性

当进行查询时可以把事务设置成只读事务。readOnly="true"

事务传播属性NESTED介绍

@Resource OtherService otherService

public void xxx() {

  stmt.exectuteUpdate("update person set name='888' where id=1");

  otherService.update();//OtherServiceupdate方法的事务传播属性为NESTED

  stmt.executeUpdate("delete from person where id=9");

下一页则是对此程序的解释

Connection conn = null;

try {

    conn.setAutoCommit(false);

    Statement stmt = conn.createStatement();

    stmt.executeUpdate("update person set name='888' where id=1");

    Savepointsavepoint = conn.setSavepoint();

    try{  

            conn.createStatement().executeUpdate("update person set name='222' where sid=2");

    }catch(Exception ex){

            conn.rollback(savepoint);   

     }

      stmt.executeUpdate("delete from person where id=9");

      conn.commit();

       stmt.close();

    } catch (Exception e) {

         conn.rollback();

     }finally{

               try {

      if(null!=conn && !conn.isClosed()) conn.close();

                } catch (SQLException e) { e.printStackTrace(); }

     }

}

数据库系统提供了四种事务隔离级

数据库系统提供了四种事务隔离级别供用户选择。不同的隔离级别采用不同的锁类型来实现,在四种隔离级别中,Serializable的隔离级别最高,Read Uncommited的隔离级别最低。大多数据库默认的隔离级别为Read Commited,如SqlServer,当然也有少部分数据库默认的隔离级别为Repeatable Read ,如Mysql

l Read Uncommited :读未提交数据 ( 会出现脏读 , 不可重复读和幻读 )
l Read Commited :读已提交数据 ( 会出现不可重复读和幻读 )
l Repeatable Read :可重复读 ( 会出现幻读 )
l Serializable :串行化

脏读:一个事务读取到另一事务未提交的更新新据。

不可重复读:在同一事务中,多次读取同一数据返回的结果有所不同。换句话说就是,后续读取可以读到另一事务已提交的更新数据。相反,“可重复读”在同一事务中多次读取数据时,能够保证所读数据一样,也就是,后续读取不能读到另一事务已提交的更新数据。

幻读:一个事务读取到另一事务已提交的insert数据。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值