【问题标题】:Why I got no session exception error from spring jpa为什么我没有从 spring jpa 得到会话异常错误
【发布时间】:2016-08-16 13:38:22
【问题描述】:

我使用 springboot 和 spring jpa 作为我的后端框架。从 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 初始化造成的。但我不明白为什么我的代码有这样的问题。我没有关闭会话,所有呼叫都在一个 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?

【问题讨论】:

    标签: spring hibernate spring-data-jpa


    【解决方案1】:

    将类标记为@Transactional,然后Spring将处理会话管理而不是方法。 @Transactional 公共课我的课{ ... } 通过使用@Transactional,可以自动处理事务传播等许多重要方面。在这种情况下,如果调用另一个事务方法,该方法将可以选择加入正在进行的事务,从而避免“无会话”异常。

    你也可以使用传播

    【讨论】:

    • 这是否意味着@Transactional over 方法将支持休眠会话?
    • 不,它不会破坏事务,但休眠也会混淆如何处理事务,例如使用现有事务或启动新事务。因此您必须使用传播指定,例如:REQUIRED、REQUIRES_NEW、MANDATORY 等跨度>
    猜你喜欢
    • 1970-01-01
    • 2016-07-19
    • 1970-01-01
    • 1970-01-01
    • 2020-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多