2016-08-16 24 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

相关问题