LazyInitializationException:无法初始化代理-没有会话
我使用spring-data-jpa
with spring-
boot(v2.0.0.RELEASE),我只是在MySQL上编写了一个CRUD演示,但是在运行时发生了异常,源代码如下:
User.java
@Entitypublic class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private Integer id;
private String username;
private String password;
...getter&setter
}
UserRepository.java
public interface UserRepository extends JpaRepository<User, Integer> {}
UserServiceTest.java
@RunWith(SpringRunner.class)@SpringBootTest
public class UserServiceTest {
@Autowired
private UserRepository userRepository;
@Test
public void getUserById() throws Exception{
userRepository.getOne(1);
}
}
spring: datasource:
username: ***
password: ***
driver-class-name: com.mysql.jdbc.Driver
url: ********
thymeleaf:
cache: false
jpa:
show-sql: true
hibernate:
ddl-auto: update
org.hibernate.LazyInitializationException: could not initialize proxy - no Sessionat 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)
我尝试另一种方法
userRepository.findOne(1)
,它可以成功运行。
回答:
您可以@Transactional
在测试方法中添加注释,以避免出现此异常。
方法getOne
返回可以延迟加载属性的实体的“引用”(代理)。看到它的代码
-它使用的getReference
方法EntityManager
。从它javadoc:
获取一个实例,其状态可能会延迟获取。
在Spring中,其实现EntityManager
是org.hibernate.internal.SessionImpl-因此,如果没有Session,Spring将无法获得此方法。
要进行会话,您可以只创建一个交易…
以上是 LazyInitializationException:无法初始化代理-没有会话 的全部内容, 来源链接: utcz.com/qa/400545.html