java - Spring MVC + Rest API - Failed to lazily initialize a collection -


i'm building application using spring mvc. flow basic, i.e., controller --> service --> dao , back.

now, i'm creating restcontroller, call service , perform whatever want. stuck issue strange, , need help.

i have 2 entities user , role. 1 user can have many roles, , role can assigned many users - manytomany mapping. have given fetchtype.lazy both these dependencies.

everything works fine in web application when log-in via browser. but, when invoke restcontroller, following error

org.springframework.http.converter.httpmessagenotwritableexception: not write content: failed lazily initialize collection of role: com.xx.yyy.entity.role.users, not initialize proxy - no session (through reference chain: com.xx.yyy.entity.user["roles"]->org.hibernate.collection.internal.persistentbag[0]->com.xx.yyy.entity.role["users"]); nested exception com.fasterxml.jackson.databind.jsonmappingexception: failed lazily initialize collection of role: com.xx.yyy.entity.role.users, not initialize proxy - no session (through reference chain: com.xx.yyy.entity.user["roles"]->org.hibernate.collection.internal.persistentbag[0]->com.xx.yyy.entity.role["users"]) org.springframework.http.converter.json.abstractjackson2httpmessageconverter.writeinternal(abstractjackson2httpmessageconverter.java:238) org.springframework.http.converter.abstracthttpmessageconverter.write(abstracthttpmessageconverter.java:208) org.springframework.web.servlet.mvc.method.annotation.abstractmessageconvertermethodprocessor.writewithmessageconverters(abstractmessageconvertermethodprocessor.java:161) org.springframework.web.servlet.mvc.method.annotation.abstractmessageconvertermethodprocessor.writewithmessageconverters(abstractmessageconvertermethodprocessor.java:101) org.springframework.web.servlet.mvc.method.annotation.requestresponsebodymethodprocessor.handlereturnvalue(requestresponsebodymethodprocessor.java:202) org.springframework.web.method.support.handlermethodreturnvaluehandlercomposite.handlereturnvalue(handlermethodreturnvaluehandlercomposite.java:71) org.springframework.web.servlet.mvc.method.annotation.servletinvocablehandlermethod.invokeandhandle(servletinvocablehandlermethod.java:126) org.springframework.web.servlet.mvc.method.annotation.requestmappinghandleradapter.invokehandlemethod(requestmappinghandleradapter.java:777) org.springframework.web.servlet.mvc.method.annotation.requestmappinghandleradapter.handleinternal(requestmappinghandleradapter.java:706) org.springframework.web.servlet.mvc.method.abstracthandlermethodadapter.handle(abstracthandlermethodadapter.java:85) org.springframework.web.servlet.dispatcherservlet.dodispatch(dispatcherservlet.java:943) org.springframework.web.servlet.dispatcherservlet.doservice(dispatcherservlet.java:877) org.springframework.web.servlet.frameworkservlet.processrequest(frameworkservlet.java:966) org.springframework.web.servlet.frameworkservlet.doget(frameworkservlet.java:857) javax.servlet.http.httpservlet.service(httpservlet.java:620) org.springframework.web.servlet.frameworkservlet.service(frameworkservlet.java:842) javax.servlet.http.httpservlet.service(httpservlet.java:727) org.apache.tomcat.websocket.server.wsfilter.dofilter(wsfilter.java:52) org.springframework.security.web.filterchainproxy$virtualfilterchain.dofilter(filterchainproxy.java:330) org.springframework.security.web.access.intercept.filtersecurityinterceptor.invoke(filtersecurityinterceptor.java:118) org.springframework.security.web.access.intercept.filtersecurityinterceptor.dofilter(filtersecurityinterceptor.java:84) org.springframework.security.web.filterchainproxy$virtualfilterchain.dofilter(filterchainproxy.java:342) org.springframework.security.web.access.exceptiontranslationfilter.dofilter(exceptiontranslationfilter.java:113) org.springframework.security.web.filterchainproxy$virtualfilterchain.dofilter(filterchainproxy.java:342) org.springframework.security.web.session.sessionmanagementfilter.dofilter(sessionmanagementfilter.java:103) org.springframework.security.web.filterchainproxy$virtualfilterchain.dofilter(filterchainproxy.java:342) org.springframework.security.web.authentication.anonymousauthenticationfilter.dofilter(anonymousauthenticationfilter.java:113) org.springframework.security.web.filterchainproxy$virtualfilterchain.dofilter(filterchainproxy.java:342) org.springframework.security.web.servletapi.securitycontextholderawarerequestfilter.dofilter(securitycontextholderawarerequestfilter.java:154) org.springframework.security.web.filterchainproxy$virtualfilterchain.dofilter(filterchainproxy.java:342) org.springframework.security.web.savedrequest.requestcacheawarefilter.dofilter(requestcacheawarefilter.java:45) org.springframework.security.web.filterchainproxy$virtualfilterchain.dofilter(filterchainproxy.java:342) org.springframework.security.web.authentication.www.basicauthenticationfilter.dofilter(basicauthenticationfilter.java:150) org.springframework.security.web.filterchainproxy$virtualfilterchain.dofilter(filterchainproxy.java:342) org.springframework.security.web.authentication.abstractauthenticationprocessingfilter.dofilter(abstractauthenticationprocessingfilter.java:199) org.springframework.security.web.filterchainproxy$virtualfilterchain.dofilter(filterchainproxy.java:342) org.springframework.security.web.authentication.logout.logoutfilter.dofilter(logoutfilter.java:110) org.springframework.security.web.filterchainproxy$virtualfilterchain.dofilter(filterchainproxy.java:342) org.springframework.security.web.context.request.async.webasyncmanagerintegrationfilter.dofilterinternal(webasyncmanagerintegrationfilter.java:50) org.springframework.web.filter.onceperrequestfilter.dofilter(onceperrequestfilter.java:107) org.springframework.security.web.filterchainproxy$virtualfilterchain.dofilter(filterchainproxy.java:342) org.springframework.security.web.context.securitycontextpersistencefilter.dofilter(securitycontextpersistencefilter.java:87) org.springframework.security.web.filterchainproxy$virtualfilterchain.dofilter(filterchainproxy.java:342) org.springframework.security.web.filterchainproxy.dofilterinternal(filterchainproxy.java:192) org.springframework.security.web.filterchainproxy.dofilter(filterchainproxy.java:160) org.springframework.web.filter.delegatingfilterproxy.invokedelegate(delegatingfilterproxy.java:344) org.springframework.web.filter.delegatingfilterproxy.dofilter(delegatingfilterproxy.java:261) 

the strange thing here is, works fine when i'm on ui (i.e, on web application)

following entities

user.java

@entity @table(name="users")  public class user {     @id     @column (name="user_id")     private string id;      @notempty(message = "first name mandatory")     @column (name="first_name")     private string firstname;      @column (name="last_name")     private string lastname;      @notempty(message= "email id mandatory")     @column (name="email_id")     private string emailid;      @notempty(message="primary phone number mandatory")     @column (name="phone_1")     private string primaryphone;      @column (name="phone_2")     private string secondaryphone;      @column (name="pass_word")     private string password;      @manytomany(fetch = fetchtype.lazy)     @jointable( name="rolesmapping", joincolumns={@joincolumn(name="user_id")}, inversejoincolumns={@joincolumn(name="group_id")})     private list<role> roles = new arraylist<role>();       @transient     private list<string> roleids = new arraylist<string>();      //getters , setters  } 

role.java

@entity @table( name="roles" ) public class role {      @id     @column( name="group_id")     private string id;      @column( name="group_desc" )     private string description;      @manytomany(mappedby="roles")     @lazycollection(lazycollectionoption.true)     private list<user> users = new arraylist<user>();      //getters , setters go here } 

i added lazycollection annotation before posting question (after referring many other posts), din't help.

i figured there's sending response client, because tried put breakpoint in restcontroller on line after fetches user, , surprise, user fetched. error comes after that, when return user; statement executed. here's rest controller

@restcontroller @requestmapping("/api/user") public class genericcontroller {      private static final logger logger = loggerfactory.getlogger(genericcontroller.class);      @autowired     private userservice userservice;      @requestmapping("/get/{userid}")     public user get(@pathvariable(value="userid") string userid) {         try{             if(stringutils.isemptystring(userid)){                 userid = "admin";             }             user user = userservice.getuserbyid(userid);             return user;         }catch(exception e){             logger.error(e.getmessage(),e);             return null;         }     } } 

here's tried doing

i referred other posts on same error, , tried making fetch types eager (i.e, fetch=fetchtype.eager) on both entities. happened next was, user details fetched along roles, roles in-turn have users fetched along them, , happens in indefinite loop. json output never-ending.

please me understand i'm going wrong.

thanks @boris spider, looked @ this post, , answer right there!

all did solve issue add @jsonignore field in child class refers parent entity, this

@entity @table( name="roles" ) public class role {      @id     @column( name="group_id")     private string id;      @column( name="group_desc" )     private string description;      @manytomany(mappedby="roles")     @jsonignore     private list<user> users = new arraylist<user>();      //getters , setters go here } 

this solved indefinitely looping issue.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -