Spring3 @Transaction

来源:互联网 发布:java线程超时关闭 编辑:程序博客网 时间:2024/06/05 18:33

由于在dao用的是:session 而不是 hibernate Template

所以session中没有事务()

 

这就需要自己手工的配置事务,事务是配置在service

所以在配置文件appluicationContext中:

         <beanid="tx" class="org.springframework.orm.hibernate3.HibernateTransactionManager">

                   <propertyname="sessionFactory"ref="sessionFactory"></property>

         </bean>

         <!--声明  使用事务为 注解的方式!!! -->

         <tx:annotation-driventransaction-manager="tx" /

 

声明采用注解的方式声明事务!

 

由于写了一个baseServiceImpl的基类

所以各个service都继承与baseServiceImpl

 

在baseServiceImpl中


@Transactional

public class BaseServiceImpl<T ,Eextends IBaseDao<T>> implements IBaseService<T, E> {

在EmployeeServiceImpl中

@Service

public class EmployeeServiceImpl extendsBaseServiceImpl<Employee, IEmployeeDao> implements IEmployeeService {

由此可见只在baseServiceImp有l@Transactional

(案例说  在每个service中都应该添加@Transactiona

这是为什么?

因为:annotation是可以继承的,所以必须而且一定要在基类中添加@Transactional

 

倘若只在service中添加@Transactional

而基类中不添加

(即

public class BaseServiceImpl<T ,Eextends IBaseDao<T>> implements IBaseService<T, E> {

在EmployeeServiceImpl中

@Service

@Transactional

public class EmployeeServiceImpl extendsBaseServiceImpl<Employee, IEmployeeDao> implements IEmployeeService {

 

会有下面的异常

org.hibernate.HibernateException:No Hibernate Session bound to thread, and configuration does not allow creationof non-transactional one her

 

这是因为子类service会调用父类的方法,而父类中的方法并没有@Transactional

所以会出现异常!!!



<!-- 自动扫描与装配bean --><context:component-scan base-package="cn.sdu.erp"></context:component-scan><!-- 由于在配置数据源的时候  使用的是${}  所以需要引入配置文件 --><context:property-placeholder location="classpath:jdbc.properties" /><!-- 配置session工厂 --><bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"><property name="configLocation" value="classpath:hibernate.cfg.xml"></property><property name="dataSource"><!-- 配置数据源连接池信息 --><bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource"><property name="user" value="${jdbc.user}" /><property name="password" value="${jdbc.password}" /><property name="driver" value="${jdbc.driver}" /><property name="driverUrl" value="${jdbc.driverUrl}" /></bean></property></bean><!-- 配置事务管理器 --><bean id="tx" class="org.springframework.orm.hibernate3.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"></property></bean><!-- 声明  使用事务为 注解的方式!!! --><tx:annotation-driven transaction-manager="tx" /></beans>

原创粉丝点击