Need Proxy?

BotProxy: Rotating Proxies Made for professionals. Really fast connection. Built-in IP rotation. Fresh IPs every day.

Find out more


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

Question

In Employee and Phone example

How to make Hibernate Lazy initialization to work (within 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;

P.S. Some advises to use FetchType.EAGER like in https://stackoverflow.com/questions/7654818/org-hibernate-lazyinitializationexception-could-not-initialize-proxy-no-sessi, but making Lazy loading work (within Spring Boot, Spring Data JPA) is exactly my goal.

Answer

Thanks to M. Deinum for hint.

This particular case was solved by adding toString() in Employee to re-define over Lombok toString()

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

also specifying exactly Fetch type

code at https://github.com/paulvi/spring-boot-querydsl

cc by-sa 3.0