简体   繁体   中英

Handle EntityNotFoundException when saving parent entity with removed child entity from collection

My problem is simple, but yet finding the solution has become a rather tedious and difficult task.

I have two hibernate entities,

  1. Owner
  2. Dog

The Owner (or the "parent" entity) has three fields,

  1. name
  2. address
  3. dogs (a collection of Dog entities - OneToMany relationship).

When removing a Dog from the Owner 's collection (both from the object's collection and from the database via the Dog Repository), as well as updating the address of the Owner, and then trying to save the updated object in the database, the following Exception is thrown:

javax.persistence.EntityNotFoundException: Unable to find project.pets.entities.Dog with id 10

One way of working around the problem is to get the new version of the Owner once the Dog collection is updated, by calling the Owner's Repository with findOne(ownerId) , before updating the owner's address and saving the entity in the database.

But this does not seem like a proper solution.

I ought to mention that there is no caching implemented.

Has anybody come across such a thing and managed to handle it appropriately?

EDIT 1:

Sample code:

Owner:

@Entity
@Table(name = "owners")
public class Owner {

...

@Column(name = "address")
private String address;

@OneToMany(fetch = FetchType.EAGER, mappedBy = "owner", 
           cascade = {CascadeType.MERGE, CascadeType.REMOVE})
private List<Dog> dogs;

...

==================================================

Dog:

@Entity
@Table(name = "dogs")
public class Dog {

 ...

@ManyToOne
@JoinColumn(name = "owner_id")
private Owner owner;

...

==================================================

Example code:

Owner owner = ownerRepository.findOne(ownerId);
Dog firstDog = owner.getDogs().get(0); // getting the first dog of the owner

owner.getDogs().remove(0); // removing from object's collection
dogRepository.delete(firstDog); // removing from DB

owner.setAddress("new address");
ownerRepository.save(owner);

You don't need to execute dogRepository.delete(firstDog); : Owner already takes care of propagating the removal of your entry from DB. Which is the reason why you have the exception: firstDog was already being removed by Hibernate, so when you call dogRepository.delete(firstDog); again, Hibernate will complain because it cannot find your entity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM