gpt4 book ai didi

java - Spring Data JPA、Hibernate、@ManyToOne(fetch=FetchType.LAZY) 和 org.hibernate.LazyInitializationException : could not initialize proxy - no Session

转载 作者:行者123 更新时间:2023-11-30 08:01:06 24 4
gpt4 key购买 nike

Employee and Phone example

如何使 Hibernate Lazy 初始化工作(在 Spring Boot 中)?

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.example.domain.Employee_$$_jvstb7e_2.toString(Employee_$$_jvstb7e_2.java) ~[bin/:na]
at java.lang.String.valueOf(String.java:2994) ~[na:1.8.0_74]
at java.lang.StringBuilder.append(StringBuilder.java:131) ~[na:1.8.0_74]
at com.example.domain.Phone.toString(Phone.java:13) ~[bin/:na]
at com.example.SpringBootQuerydslTestBean$1.run(SpringBootQuerydslTestBean.java:49) ~[bin/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:806) [spring-boot-1.3.5.RELEASE.jar:1.3.5.RELEASE]
... 6 common frames omitted

Java code

public class Phone {
...
@ManyToOne(fetch=FetchType.LAZY)
private Employee owner;

附言有些人建议使用 FetchType.EAGER,如 org.hibernate.LazyInitializationException: could not initialize proxy - no Session ,但是让延迟加载工作(在 Spring Boot、Spring Data JPA 中)正是我的目标。

最佳答案

感谢 M. Deinum 的提示。

这个特殊情况通过在 Employee 中添加 toString() 来重新定义 Lombok toString()

来解决
@Override
public String toString() {
return "Employee [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + "]";
}

还有specifying exactly Fetch type

代码在 https://github.com/paulvi/spring-boot-querydsl

关于java - Spring Data JPA、Hibernate、@ManyToOne(fetch=FetchType.LAZY) 和 org.hibernate.LazyInitializationException : could not initialize proxy - no Session,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37984610/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com