java LazyInitializationException:无法初始化代理 - 没有会话

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49894587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 10:28:47  来源:igfitidea点击:

LazyInitializationException: could not initialize proxy - no Session

javaspring-bootspring-dataspring-data-jpa

提问by Shuai Junlan

I use spring-data-jpawith spring-boot(v2.0.0.RELEASE), I just wrote a CRUD demo on MySQL, but an exception occurs during runtime, source code as follows:

我用spring-data-jpawith spring-boot(v2.0.0.RELEASE),刚在MySQL上写了一个CRUD的demo,但是运行时出现异常,源码如下:

Source code

源代码

User.java

用户.java

@Entity
public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    private Integer id;
    private String username;
    private String password;

    ...getter&setter
} 

UserRepository.java

用户存储库.java

public interface UserRepository extends JpaRepository<User, Integer> {

}

UserServiceTest.java

用户服务测试.java

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceTest {

    @Autowired
    private UserRepository userRepository;

    @Test
    public void getUserById() throws Exception{
        userRepository.getOne(1);
    }

}

application.yml

应用程序.yml

spring:
  datasource:
    username: ***
    password: ***
    driver-class-name: com.mysql.jdbc.Driver
    url: ********
  thymeleaf:
    cache: false
  jpa:
    show-sql: true
    hibernate:
      ddl-auto: update

Exception details

异常详情

org.hibernate.LazyInitializationException: could not initialize proxy - no Session

at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:155)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:268)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:73)
at cn.shuaijunlan.sdnsecuritysystem.domain.po.User_$$_jvstc90_0.getUsername(User_$$_jvstc90_0.java)
at cn.shuaijunlan.sdnsecuritysystem.service.UserServiceTest.getUserById(UserServiceTest.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)

I try to another method userRepository.findOne(1), it can run successfully.

我尝试了另一种方法userRepository.findOne(1),它可以成功运行。

回答by Cepr0

You can add @Transactionalannotation to your test method to avoid this exception.

您可以@Transactional向测试方法添加注释以避免此异常。

Method getOnereturn the 'reference' (proxy) of the entity which properties can be lazy loaded. See it code- it uses getReferencemethod of EntityManager. From it javadoc:

方法getOne返回可以延迟加载属性的实体的“引用”(代理)。看到它的代码-它使用getReference的方法EntityManager。从它javadoc:

Get an instance, whose state may be lazily fetched.

获取一个实例,其状态可能会被延迟获取。

In Spring the implementation of EntityManageris org.hibernate.internal.SessionImpl- so without the Session the Spring can not get this method.

在 Spring 中的实现EntityManagerorg.hibernate.internal.SessionImpl- 所以没有 Session Spring 无法获得这个方法。

To have a session you can just create a transaction...

要进行会话,您只需创建一个事务...

回答by mukesh kumar

Your test should be like this:

你的测试应该是这样的:

@RunWith(SpringRunner.class)    


@SpringBootTest
@Transactional    

public class QuestionTesting {   

    @Test    
    public void test() {    

    }    
}    

回答by KayV

In the service class please add a setter for entity manager by using the annoattion @PersistenceContext. To be specific, use

在服务类中,请使用注解@PersistenceContext 为实体管理器添加一个setter。具体来说,使用

 @PersistenceContext(type = PersistenceContextType.EXTENDED)

In this way, you can access lazy property.

通过这种方式,您可以访问lazy 属性。