Reputation: 106
I have an entity called "House" that contains multiple "Room"s, which is setup as follows:
House.java:
@Entity
public class House {
@OneToMany(mappedBy = "house", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Item> rooms;
...
}
Room.java:
@Entity
public class Room {
@ManyToOne
@JoinColumn(name = "houseId")
private House house;
...
}
Now, if I delete a room directly via the entity manager it is not deleted:
getEntityManager().contains(room); // returns true
getEntityManager().remove(room);
getEntityManager().flush();
If I delete it from the collection, it is deleted:
house.getRooms().remove(room);
getEntityManager().persist();
getEntityManager().flush();
Can anyone explain me this behavior? Thanks!
Upvotes: 4
Views: 2204
Reputation: 18403
In second example you have to persist
house to make room remove effective.
In first code you are removing object from EntityManager persistence context
(and entity manager register you deletion) and flush()
apply this operation removing room from database.
In second example you call List.remove()
: you are not advice EntityManager
to delete object from database; orphanRemoval
will works when you call entityManager().persist(house)
because when you do house.getRooms().remove(room)
you are modify house and need to tell entityManager to apply this modification with EntityManager.persist()
; orphanRemoval
do the rest deleting removed room because detected as orphan
Upvotes: 1