5
4
|
Do cascades hold only when I specify them on the entity owning the relationship ? from http://stackoverflow.com/questions/1534599/a-question-on-jpa-cascading I have two entities called User and UserProfile in my datamodel. Here is how they are mapped. Code from User Entity:
Code from UserProfile Entity:
As you see, I have a cascadetype.all for the user attribute in UserProfile. But when I try deleting the UserProfile entity, the corresponding User entity still stays. (When I try deleting the User entity, corresponding UserProfile entity gets deleted.) Here is my question:-
|
||||||
feedback
|
4
|
Your question is wrong in and of itself, which is where all the confusion stems from. Arthur did a good job with his answer but it's clear from the comments the the confusion still remains so let me take a stab at it here.
"cascade" is an attribute you specify on one (or possibly both in case of bi-directional) end of a relationship. It determines what actions performed on that end will be propagated to the other end. There are many different types of those actions defined in JPA and even more defined in Hibernate extensions. This distinction is important - you should only talk about specific behavior being propagated and not "cascade" in general. PERSIST, MERGE, REFRESH propagate normally (from the end they were declared on to the other).
REMOVE, however, is tricky because it can mean two different things. If you have a relationship betweenA and B and
you're trying to remove A,
you can either remove B on
the other end OR you can remove the association but
leave B intact.
Hibernate makes a clear distinction between the two - you can declare REMOVE (DELETE) and
Thus, propagation of REMOVE (by itself or when it's part of ALL) depends on whether relationship has a clear owner (uni-directional always does; bi-directional does if it's mapped using mappedBy and
does not if it's mapped via join
table) in which case it's propagated from owner to owned OR no owner in which case it's propagated in either direction but without |
||
feedback
|
1
|
As said
Maybe when you try to remove a UserProfile you get an integrity constraint violation from the database - do you use MyISAM engine in MySQL ? But as you does not says nothing about it. Maybe your UserProfile entity does not have a reference to a User entity. As said in JPA specification
Something like
Or you have something like
In response to ChhsPly's comment: In Java Persistence with Hibernate book, you see the following
I think it would be better as
So you can put cascade attribute in both sides at the same time, even in a bidirectional relationship. So ChssPly is right. mappdeBy attribute sets up the bidirectional relationship. mappedBy attribute designated the Address entity as the inverse side of the relationship. This means that the Customer entity is the owning side of the relationship. ChssPly is right when he says mappedBy has nothing to do with cascading |
||||||||||
|