2016-08-16 33 views
0

我使用springboot和spring jpa作爲我的後端框架。當從jpa存儲庫訪問實體時,我得到了以下異常。爲什麼我從Spring沒有得到會話異常錯誤jpa

2016-08-16 20:39:27.528 ERROR 19243 --- [http-nio-8090-exec-8] [.[.[.[.c.c.Go2NurseJerseyConfiguration] : Servlet.service() for servlet [com.cooltoo.config.Go2NurseJerseyConfiguration] in context with path [] threw exception [org.hibernate.LazyInitializationException: could not initialize proxy - no Session] with root cause 

org.hibernate.LazyInitializationException: could not initialize proxy - no Session 
    at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:165) ~[hibernate-core-4.3.11.Final.jar!/:4.3.11.Final] 
    at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:286) ~[hibernate-core-4.3.11.Final.jar!/:4.3.11.Final] 
    at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:185) ~[hibernate-core-4.3.11.Final.jar!/:4.3.11.Final] 
    at com.cooltoo.go2nurse.entities.UserEntity_$$_jvst80d_8.getPassword(UserEntity_$$_jvst80d_8.java) ~[com.cooltoo.go2nurse-common-1.0.0-SNAPSHOT.jar!/:na] 

經過一番搜索後,我發現這是由於hibernate laze initialize。但我不明白的是爲什麼我的代碼有這樣的問題。我沒有關閉會話,所有的呼叫都在一個http請求中。以下是我的代碼:

@Transactional 
private UserBean registerWithChannel(String name, int gender, String strBirthday, String mobile, String password, String smsCode, String channel, String channelid) { 
     currentUser = repository.findByMobile(mobile); 
     //already existed such user, link with channel user 
     UserBean userBean = updatePassword(currentUser.getId(), currentUser.getPassword(), password); 
     loginService.login(mobile, password); 

} 

@Transactional 
public UserBean updatePassword(long userId, String oldPassword, String newPassword) { 
     logger.info("modify the password by userId={} oldPwd={} newPwd={}", 
       userId, oldPassword, newPassword); 

     UserEntity user = repository.getOne(userId); 
     if (null==user) { 
      throw new BadRequestException(ErrorCode.RECORD_NOT_EXIST); 
     } 

     boolean changed = false; 

     // check password 
     if (user.getPassword().equals(oldPassword)) { //the exception happens here 

     } 
     ... 
    } 

@Transactional註釋有什麼問題嗎?或者是因爲我在兩種方法中使用相同的UserEntity?

回答

0

將類標記爲@Transactional,那麼Spring將處理會話管理而不是方法。 @Transactional public class My Class { ... } 通過使用@Transactional,很多重要的方面(如事務傳播)都會自動處理。在這種情況下,如果調用另一個事務方法,則該方法可以選擇加入正在進行的事務,避免出現「無會話」異常。

您也可以使用傳播

+0

這是否意味着@Transactional方法將麪包休眠會話? –

+0

不,它不會中斷事務,但hibernate也會對使用現有事務或開始新事務處理事務該怎麼辦。因此,您必須指定傳播類似於:REQUIRED,REQUIRES_NEW,MANDATORY ETC – Abhishek

相關問題