I have tow classes:
In the database Child table has a column ParentId -> typical One (Parent) -> Many (Children) relation
Now I create two entities and they
public class Parent
{
@OneToMany(mappedBy="Parent", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
public Set<Child> getChildern()
{
...
}
}
public class Child
{
@ManyToOne(fetch = FetchType.EAGER, cascade=CascadeType.ALL)
@JoinColumn(name="ParentId")
public Parent getParent()
{ ... }
}
Now I have two scenarios:
Bonus questions:
First of all I'm surprise this code works at all. IMO mappedBy="Parent"
should actually be mappedBy="parent"
(note the lower-case 'p') because the parent property of the Child
class is called parent
and not Parent
.
Second, I suggest you place the annotations on the properties rather than on the accessor methods. I find it makes the whole code
Answers to your questions depend on what exactly you mean by "get deleted". I assume you mean "deleted through persistence manager".
BUT just in case you expect/want that a child is removed by the JPA provider if you do parent.getChildren().remove(x)
then you need to set orphanRemoval = "true"
on OneToMany
.
Question 1
Parent and all children are deleted. That's the common case.
Question 2
Parent and all children are deleted. That's a rather odd use case. Usually cascade delete is only applied on the one-to-many relationship.
Bonus 1
All relationships in Java and JPA are unidirectional, in that if a source object references a target object there is no guarantee that the target object also has a relationship to the source object.
from the excellent Java Persistence wiki book .
Bonus 2
Dunno. Is the ConstraintViolationException
coming from the underlying data base? Or put differently, how does the DDL for the two tables look like? Was it generated by Hibernate?
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.