I have a project which uses Spring, Hibernate, and has controllers which return JSONs. Naturally, my models contain lists and such to use JPA annotations to define the hibernate relationships, so, for example, I have Users, which contain a set of Challenges they own, and likewise Challenge contains a User who owns it.
Unfortunately I seem to be having a lot of issues with collections embedded in my JSONs.
For example, with that set up (a User owns challenges and a challenge has a owner) I can return a Challenge just fine. I can return a User just fine. But when I try to return a list of challenges, everything blows up! I receive the following error from my Jmeter test:
Error 500 Server Error
I believe this means that the Jackson json parser had an issue setting the json. I believe this, because if I use @JsonIgnoreProperties({“challengesOwned”}) then I can return the list of challenges just fine, since each individual challenge object no longer has a list embedded inside it.
This seems very strange to me. Can Jackson really not map simple embedded lists within JSONs? I’ve also got a huge problem because I have a Map which uses a User as its key … and it seems it’s not even possible to define a JSON map’s key as an embedded object at all!
Does anyone have a suggestion for my issue? Do I have to manually define some Json mappings? Is there a simple solution I just don’t know about?
EDIT:
While what j0ntech says does seem to have been true, it turns out that was not the whole story. It seems that when Spring used Jackson to serialize one of my hibernate entities into it’s JSON version, hibernate was trying to lazy load one of that entity’s properties, but since the entity was outside of its transaction at that point (being “in” the controller), it caused an exception, which just got swallowed up.
So there were actually TWO issues. I figured this out by trying to manually use Jackson to serialize the object I was returning before actually returning it. That way I actually got the stack trace for the other issue.
You probably have a recursive loop (as per DwB’s comment): User contains a list of Challenges, which each contain a User, which contains a list of Challenges and so on and so forth. The parser (or your server at large) doesn’t like that. You should use the annotations JsonManagedReference and JsonBackReference.
You can read about how to use these annotations here and here. I’ve used them in some of my own projects and they work very well if correctly implemented.