Hibernate inserts duplicate child on cascade
- Get link
- X
- Other Apps
At times we all use hibernate's cascade feature to cascade the child entries into database for OneToMany and ManyToMany relationships. If it is a first entry in DB then everything works fine but when we want to update the number/quantity of child of an existing parent, hibernate adds duplicate children. Assume the parent already exists with few children. Below is the relationship:
Parent Mapping for OneToMany with Child:
@OneToMany(targetEntity = ChildrenImpl.class, mappedBy = "parent", orphanRemoval = true, fetch = FetchType.LAZY) @Cascade(value = CascadeType.ALL) private List<Children> children = new ArrayList<Children>();
Child Mapping with parent ManyToOne
@ManyToOne(targetEntity = ParentImpl.class, fetch = FetchType.LAZY) @JoinColumn(name = "PARENT_ID") private Parent parent;
Below is the code which leads to duplicate children.
Children newChild = new ChildrenImpl(); newChild.setName("I am a new child"); /* More setters here */ ... parent.getChildren().add(newChild); /** More business logic here **/ entityManager.merge(parent); // OR session.merge(parent); whatever implementation exists
At this point if you check DB, there will be 2 rows for this new child. To solve this problem there are 2 ways:
1) Update the mapping annotation to load the children in parent eagerly using fetch = FetchType.EAGER at @OneToMany
2) Just before adding the new child into the existing child list/set, load the existing children forcefully by calling size() or any operation like isEmpty() which leads to load entire object in memory of that List or Set.
- Get link
- X
- Other Apps
Comments
What an amazing and useful article. Looks like I have became fan of yours!
ReplyDeleteEvery time I surf the internet, I lend on your blog and never go back empty handed :)
Keep up the good work!
Great post.
ReplyDeleteThis bug report (https://hibernate.atlassian.net/browse/HHH-6776) is probably related with this behavior. Are you using the hibernate embedded in some application server? If yes, which one?
Thanks!
I really appreciate this short information which you uploaded above. It’s of nice help. If someone want to take Child Development services or other types products and other facility in low budget then kindly contact us. We provide professional services. aristotots.ca has successfully conducted 1000+ etc. Please explore this site and visit.
ReplyDeleteAfter searching endlessly for a solution on why hibernate is reporting errors or attempting to insert duplicates, I finally found this site. After changing my annotations the save worked PERFECTLY! I wish everyone could keep their explanations as short and to the point as you. Great work.
ReplyDeleteI've spent years on trying to find the solution AND HERE IT IS, thank GOD for your existence my dearest friend.
ReplyDelete