2
@Entity
public class Post {

private Set<Comment> comments = new LinkedHashSet<Comment>();

@OneToMany(mappedBy = "businessunit", fetch = FetchType.LAZY, cascade = { CascadeType.ALL }, orphanRemoval = true)
public Set<Comment> getComments() {
  return comments;
}
} 

@Entity
public class Comment {

private Post Post;
private BUnit bUnit;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "POST_ID", referencedColumnName = "ID")
public Post getPost() {
    return post;
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "BU_ID", referencedColumnName = "ID")
public BUnit getBUnit() {
    return bUnit;
}
}

I have a Parent class containing Set of children. Add operation works fine as I add the comment's to Set and when I save the parent, children are saved too.

For update operation, I will be having an existing comment and new comment. I update the modified_by field for the existing comment and for the new comment I set its desired fields. Next I clear the set and add all the comments(new and existing one) so as I do not get all-delete-orphan error.

post.getComments().clear();
post.getComments().addAll(newComments);
dao.update(post);

Update throws exception org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role:

Any ideas how to fix this problem for update where the child elements will contain a new and existing element.

Thanks.

Tabho
  • 31
  • 1
  • 7

2 Answers2

0

For starters, your mappedBy = "businessunit" needs to refer to the property name on the other side, in this case, post.

If you're still seeing the exception, you can look here. (There are multiple reasons for this exception.)

Lastly, and a minor point, you don't need to explicitly label fetch = FetchType.LAZY since that's the default. You can remove this to improve readability.

Community
  • 1
  • 1
riddle_me_this
  • 8,575
  • 10
  • 55
  • 80
0

I found the solution. Update was executed under transaction and is working pretty fine. Outside of the transaction I was accessing the db model child objects to convert to the ui model. This was the reason for exception also I did not required to access the child elements so eventually I removed it.

Tabho
  • 31
  • 1
  • 7