java - Hibernate LazyInitializingException -
java - Hibernate LazyInitializingException -
for example, have 2 classes. first
@entity @table(name = "employee") public class employee implements serializable{ @manytoone @joincolumn(name = "office_address_id") private address address; //setters , getters }
and second:
@entity @table(name = "address") public class address implements serializable{ @onetomany(mappedby = "address") private list<employee> employeelist; //setters , getters }
so if wand read employee
database, read address
field. address
have employeelist
lazyinitializingexception. but don't want know employeelist
. wanna know employee.getaddress()
. wand send json object employee
. @ client-side have failed load resource: server responded status of 500 (internal server error)
reason of lazyinitializingexception .
may use:
<bean id="entitymanagerfactory" class="org.springframework.orm.jpa.localcontainerentitymanagerfactorybean"> <property name="datasource" ref="datasource"/> <property name="persistenceunitname" value="mypersistenceunit"/> <property name="packagestoscan" value="com.itechart.model"/> <property name="jpavendoradapter"> <bean class="org.springframework.orm.jpa.vendor.hibernatejpavendoradapter"> <property name="databaseplatform" value="org.hibernate.dialect.mysql5innodbdialect"/> <property name="showsql" value="false"/> <property name="generateddl" value="true"/> </bean> </property> <!-- use--!> <property name="jpaproperties"> <props> <prop key="hibernate.enable_lazy_load_no_trans">true</prop> </props> </property> <!-- end use--!> <property name="persistenceprovider"> <bean class="org.hibernate.jpa.hibernatepersistenceprovider"></bean> </property> </bean>
your json
mapper might access address.employeelist
after hibernate
session closed. why sends lazyinitializingexception
.
you can seek of below solutions solve issue.
1 ) exclude employeelist
json
mapping
in jackson
can adding @jsonignore
@jsonignore public list<employee> getemployeelist() { }
2 ) initialize employeelist
before send json
mapper.
you can calling employeelist.size()
method
3 ) can alter fetchtype eager below
@onetomany(mappedby = "address", fetch = fetchtype.eager) private list<employee> employeelist;
java hibernate lazy-initialization
Comments
Post a Comment