i have no deep knowledge of Gson/Jackson till now. Please bear with me. I have to convert my object into json string. i have tried both Gson and Jackson. My object has a collection which has Fetch by default which is Lazy load. When i get the object with session.get
and convert using Gson's gson.toJson(object);
it fails to initialize that lazy collection.
1. I don't want to fetch eager.
2. i don't want to ignore it either.
I just want any way that it should return null or empty whatever instead of messing with lazy load collection. Because as far as i know, if its hibernate dependent then it is impossible fetching it out of session. Is there any work around (in both Gson or Jackson) with this issue cox i don't want to always initialize collection(but sometimes for sure)
@Entity
@JsonInclude(Include.NON_NULL)
public class Category {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
@ManyToMany
private List<Item> itemList;
//getter setter
}
And in main method
Session s = sessionFactory.openSession();
Transaction t = s.getTransaction();
t.begin();
Category category = null;
try{
category = s.get(Category.class, 1);
t.commit();
}catch(Exception e){
e.printStackTrace();
}finally{
s.close();
}
try {
Gson json = new Gson();
String categoryString = json.toJson(category);
System.out.println(categoryString);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
it throws
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.company.entity.Category.itemList, could not initialize proxy - no Session