Reputation: 14731
I am using JPA 2.
I would like to know the following.
What is the best approach to restrict insert, update or delete when parent key does not exist in parent table.
I have the following Entity scenario
@Entity
public class Employee {
@OneToMany(mappedBy = "requester")
private Set<Project> requestedProjects;
@OneToMany(mappedBy = "approver")
private Set<Project> approvedProjects;
}
@Entity
public class Project
@ManyToOne
@JoinColumn(name = "EMPLOYEE_NUMBER", referencedColumnName = "EMPLOYEE_NUMBER")
private Employee requester;
@ManyToOne
@JoinColumn(name = "APPROVER", referencedColumnName = "EMPLOYEE_NUMBER")
private Employee approver;
}
What is my limited understanding of this matter is usage of cascade=cascadeType.ALL
does insert and delete if parent key doesn't exist.
And what is the difference between MERGE
, PERSIST
and ALL
?
fetch = FetchType
Any help is highly appreciable
Upvotes: 1
Views: 4530
Reputation: 21145
These are separate questions. 1) Cascade settings do what the name suggests: when you call entityManager persist, merge or remove it performs the operation on the entity passed in. This call then gets cascaded to referenced entities depending on the mapping settings, as if you explicitly called that method on the referenced entity. So Project->requester, if you call persist on Project, it would call persist on both the project and the requester employee if either cascade persist or all types are specified. So if the employee exists but is detached, it will cause an exception either immediately or on flush/commit depending on your provider, just as if you called em.persist(employee) directly. Merge and remove operate the same way following their own restrictions and behavior outlined by the JPA specification.
CascadeType.All is just a convenient way of listing all the cascade types: REMOVE, PERSIST and MERGE without having to type them out.
You should use them when they make sense, and not just mark every relationship as CascadeType.ALL. There are plenty of tutorials that can help
2) fetch type determines when the fetch occurs. Lazy is usually recommended, which is why it is the default for collection mappings in the JPA specification, as bringing in objects unnecessarily can waste resources. But it all depends on your application's usage patterns, and how you have optimized your provider, database and mappings. Using the defaults, reading in a Project will not cause all referenced Employees to be read in, until the collection is triggered. But reading in an Employee will cause its project to be read in from the database. Care should be taken that by reading in a single entity instance, you do not mistakenly read in the entire database - which is common if you have eager collection mappings.
Upvotes: 2