java学习

java学习

 

用注解的方式加事务

在applicationContext.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:p
="http://www.springframework.org/schema/p"
         xmlns:aop
="http://www.springframework.org/schema/aop"
         xmlns:tx
="http://www.springframework.org/schema/tx"
       xmlns:context
="http://www.springframework.org/schema/context"
       xsi:schemaLocation
="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd

">
<!-- 使用注解支持事务 -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- 添加jdbc的任务管理器 -->
<bean  id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass"  value="com.mysql.jdbc.Driver"/>
<property name="jdbcUrl"  value="jdbc:mysql:///mydb"/>
<property name="properties">
<props>
    
<prop key="user">root</prop>
    
<prop key="password">root</prop>
    
</props>
</property>
</bean>
<bean id="simpleJdbcTemplate"  class="org.springframework.jdbc.core.simple.SimpleJdbcTemplate">
    
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
<!-- 在使用事务时不能配置jdbc模板,只能配置数据流 -->
<bean  id="userdao" class="com.yjw.dao.UserDao">
    
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="userService"  class="com.yjw.service.UserService">
    
<!-- name的值只和set方法后面的有关,要一样 -->
    
<property name="dao"  ref="userdao"></property>
</bean>
</beans>在service里加:
//在类的头上加上这个注解,代表这个类的所有方法都加上了事务,
//作用是某个方法里的代码要么都执行,要么都不执行
//默认是在发生RunTimeException是才回滚,发生Exception不回滚
//加上(rollbackFor=Exception.class)表示所有的异常都回滚
@Transactional(rollbackFor=Exception.class)
public class UserService {

    
private  UserDao  userdao;
    
    

    
public void setDao(UserDao userdao) {
        
this.userdao = userdao;
    }

    
    
public  void  save(User user){
        userdao.save(user);
    }

    
//只读,会使性能提高,推荐使用
    @Transactional(readOnly=true)
    
public  User findById(int id){
        
return userdao.findById(id);
    }

}

posted on 2012-05-03 22:16 杨军威 阅读(2957) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜