0

I have a very strange situation to handle in Spring and returning Json using faster jackson. I have defined the main object structure in the below way,

class Obj1
{

@OneToMany(fetch = FetchType.LAZY, mappedBy = "field1")
List<Obj2> objs2;

//Getter and Setter methods

}

Having an object structure like that resulted in exception,

nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role

Which is clear according to spring concepts that, when the faster jackson is trying to retrieve the data LAZILY as I asked it to, the session factory at that particular time is not present and hence it is throwing this kind of exception as to unable to initialize a collection of the role LAZILY.

To avoid this problem it is clear that by making fetchType to EAGER. But that is not what I am looking for,

Making it to EAGER triggers an extra query which might be unnecessary in few cases. Yes I need the list of Object2 types only in few cases. You might be thinking of JsonView now. Yes this works but does not stop querying the backend which is affecting my application.

Hence I am looking for a solution which still keeps LAZY and tries to fetch the data dynamically without creating this problem. I strongly believe that spring will definitely has that capability and there will be an alternative to handle this situation.

Kiran Joshi
  • 746
  • 1
  • 11
  • 27
  • Sir actually i also had a doubt on how lazy fetch is being handled how it works basically, if you can quote an example it wil be kind of you. – Deepanjan Jun 24 '16 at 14:52
  • 1
    A good example is given in the site here, https://howtoprogramwithjava.com/hibernate-eager-vs-lazy-fetch-type/ – Kiran Joshi Jun 27 '16 at 09:34

0 Answers0