java - Hibernate HttpMessageNotWritableException -


i using hibernate 4.3.5 in spring mvc 4.2.3. have 2 model user , client, id of user foreign key of client.

in user class:

@repository @transactional public class userdaoimpl implements userdao {  @autowired private sessionfactory sessionfactory;  protected sessionfactory getsessionfactory() {     try {         return (sessionfactory) new initialcontext().lookup("sessionfactory");     } catch (exception e) {         log.error("could not locate sessionfactory in jndi", e);         throw new illegalstateexception("could not locate sessionfactory in jndi");     } }  @onetomany(fetch = fetchtype.eager, mappedby = "user") public set<client> getclients() {     return this.clients; }  ...... } 

and in client, set:

@manytoone(fetch = fetchtype.lazy) @joincolumn(name = "user_id", nullable = false) public user getuser() {     return this.user; } 

the sessionfactory defined in root-context.xml. in way, should able clients detached user object, right? however, when ran code:

results.addall(userdao.findbyid(id).getclients()); 

it returned following exception:

warn : org.springframework.web.servlet.mvc.support.defaulthandlerexceptionresolver - failed write http message: org.springframework.http.converter.httpmessagenotwritableexception: not write content: infinite recursion (stackoverflowerror) (through reference chain: com.hersbitcloud.cancercloud.models.client["user"]->com.hersbitcloud.cancercloud.models.user["clientss"]->org.hibernate.collection.internal.persistentset[0]->com.hersbitcloud.cancercloud.models.client["user"]->com.hersbitcloud.cancercloud.models.user["clients"]->org.hibernate.collection.internal.persistentset[0]- java.lang.illegalstateexception: cannot call senderror() after response has been committed 

the stack trace extremely long, think, means when user, fetches client @ same time because eager. user object fetched again inner object of client, even set lazy. process go , froth, never stop.

i understand lazy fetch stuffs in session. question is, why session user never expired?

it because models (entities) have bidirectional mapping. when jackson tries serialize objects faces user.getclients()[0].getuser().getclients().... recursive chain. because directly use entities on presentation layer.

you can few things.

  1. use dtos
  2. use @jsonignore on entity directly (i don't prefer dao/mvc mixing)
  3. may more options

this answer has better ways it


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -