I have these two classes with OneToMany relationship :
Post.java :
@OneToMany(mappedBy = "post")
private List<Comment> comments;
Comment.java :
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "idPost")
private Post post;
I am trying to get posts with their comments posted after some date. This is my method :
@Override
public List<Post> findPostsWithCommentsAfterYesterday() {
List<Post> result = new ArrayList<>();
try {
session.getCurrentSession().beginTransaction();
Criteria criteria = session.getCurrentSession().createCriteria(Post.class);
result = (List<Post>) criteria.createAlias("comments", "cms")
.add(Restrictions.gt("cms.date", yesterday)).list();
session.getCurrentSession().getTransaction().commit();
} catch (Exception exception) {
exception.printStackTrace();
}
//
return result;
}
The list returns corresponding comments but with this exception :
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.farouk.Post.comments, no session or session was closed
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:358)
at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:350)
at org.hibernate.collection.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:343)
at org.hibernate.collection.AbstractPersistentCollection.read(AbstractPersistentCollection.java:86)
at org.hibernate.collection.PersistentBag.iterator(PersistentBag.java:249)
at org.codehaus.jackson.map.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:45)
at org.codehaus.jackson.map.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:23)
at org.codehaus.jackson.map.ser.std.AsArraySerializerBase.serialize(AsArraySerializerBase.java:86)
at org.codehaus.jackson.map.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:446)
at org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:150)
no session or session was closed ?
I know i am closing the session but after getting the list.
So what's the best practice when dealing with such situations ?