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

Shu*_*lan 6 java spring-data spring-data-jpa spring-boot

我用spring-data-jpa用spring-boot(v2.0.0.RELEASE),只是写在MySQL凝乳演示,但它如下发生运行时异常,源代码如下:

源代码

User.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
} 
Run Code Online (Sandbox Code Playgroud)

UserRepository.java

public interface UserRepository extends JpaRepository<User, Integer> {

}
Run Code Online (Sandbox Code Playgroud)

UserServiceTest.java

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

    @Autowired
    private UserRepository userRepository;

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

}
Run Code Online (Sandbox Code Playgroud)

application.yml

spring:
  datasource:
    username: ***
    password: ***
    driver-class-name: com.mysql.jdbc.Driver
    url: ********
  thymeleaf:
    cache: false
  jpa:
    show-sql: true
    hibernate:
      ddl-auto: update
Run Code Online (Sandbox Code Playgroud)

例外细节

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$1.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)
Run Code Online (Sandbox Code Playgroud)

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

Cep*_*pr0 10

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

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

获取一个实例,其状态可能会被懒惰地取出.

在Spring中实现的EntityManager是org.hibernate.internal.SessionImpl - 所以没有Session,Spring就无法获得这个方法.

要进行会话,您只需创建一个交易......