SpringMVC @Transactional的陷井大坑引發No Session found for current thread

茅坤寶駿氹發表於2018-05-03

一、TransactionManager事務配置

(1)註解配置

配置spring的xml加@Transactional
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />  

(2)xml配置

<tx:advice id="txAdvice" transaction-manager="transactionManager">  
    <tx:attributes>  
        <tx:method name="*" read-only="true" />  
        <tx:method name="save*" propagation="REQUIRED" />  
        <tx:method name="update" propagation="REQUIRED" />  
        <tx:method name="delete" propagation="REQUIRED" />  
    </tx:attributes>  
</tx:advice>  
<aop:config proxy-target-class="true">  
    <aop:pointcut expression="execution(public * com.mk.dao.impl.*.*(..))" id="servicePointcut" />  
    <aop:advisor advice-ref="txAdvice" pointcut-ref="servicePointcut" />  
</aop:config>  

二、@Transactional

(1)事務使用jdk介面動態代理

  暫無


(2)事務使用CGLIB類代理

需要設定spring的xml配置proxy-target-class="true"

<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />  

1.大坑

@Transactional註解的類無法賦予繼承的方法事務

如:

public abstract class Service<T extends Serializable,D extends Dao<T>> implements IService<T> {  
  
      
    protected D dao;  
  
    @Autowired  
    public void setDao(D dao) {  
    this.dao = dao;  
    }  
  
    //@Transactional  
    @Override  
    public T get(Integer id) {  
          
        if(Utils.isNull(id))  
            return null;  
          
        return dao.get(id);  
    }  
}  

@Transactional  
@org.springframework.stereotype.Service  
public class UserService extends Service<User, UserDao> {  
  
}  

即在呼叫UserService的get方法時會丟擲No Session found for current thread異常


2.中坑

@Transactional註解在介面或介面的方法,事務失效,CGLIB無法從繼承中獲取Transactional註解


3.小坑

@Transactional註解在public方法才有效,其他protected等方法都不起事務作用


相關文章