Java Hibernate json infinite recursion with self referencing class -
class employee:
@entity @table(name = "employee") public class employee { @id @generatedvalue(strategy = generationtype.auto) @column(name = "employeeid") private int employeeid; @column(name = "managerid") private integer managerid; @manytoone(cascade={cascadetype.all}) @joincolumn(name="managerid", insertable = false, updatable = false) @jsonbackreference private employee manager; @onetomany(mappedby="manager") @jsonmanagedreference private set<employee> employees; @manytoone(cascade={cascadetype.all}) @joincolumn(name = "departmentid") private department department; @manytoone(cascade={cascadetype.all}) @joincolumn(name = "salarytypeid") private salarytype salarytype; @column(name = "name") private string name; //setters , getters here, wont posting them }
whenever create instance of employee infinite json error:
severe: servlet.service() servlet [springmvc] in context path [/springmvc] threw exception [handler processing failed; nested exception java.lang.stackoverflowerror] root cause java.lang.stackoverflowerror @ java.nio.charbuffer.<init>(unknown source) @ java.nio.heapcharbuffer.<init>(unknown source) @ java.nio.charbuffer.wrap(unknown source) @ sun.nio.cs.streamencoder.implwrite(unknown source) @ sun.nio.cs.streamencoder.write(unknown source) @ sun.nio.cs.streamencoder.write(unknown source) @ java.io.outputstreamwriter.write(unknown source) @ java.io.writer.write(unknown source) @ com.google.gson.stream.jsonwriter.string(jsonwriter.java:534) @ com.google.gson.stream.jsonwriter.writedeferredname(jsonwriter.java:402) @ com.google.gson.stream.jsonwriter.value(jsonwriter.java:495)
(and keeps going)
since self referencing manager employee in employee class, how can fix this?
there bunch of options depends on requirement:
1) @jsonignore
can used avoid serialization of field.
@onetomany(mappedby="manager") @jsonignore private set<employee> employees;
2) @jsonview
can hide 1 part of relationship internal view (but appear if write json object internal
view):
@onetomany(mappedby="manager") @jsonview(views.internal.class) private set<employee> employees; @manytoone(cascade={cascadetype.all}) @joincolumn(name = "departmentid") @jsonview(views.public.class) private department department;
3) using custom serialiazer can determine rules of building json object yourself.
4) using @jsonidentityinfo
on classes (to indicate properties of type should have feature enabled) on individual properties (to support cases type can not annotated; or use different id generation sequence).
Comments
Post a Comment