Reputation: 1018
I have seen a couple of examples on the Internet about using JoinColumn like the way in the example below.
Actually, there are two questions I want to ask you about this partcular example. Can't we just get rid of the "optional" parameter by adding a "nullable=false" parameter to the JoinColumn. Are there any differences between optional and nullable entity relationship-wise?. What are the advantages of setting insertable and updatable to false in the joincolumn? Is this done to ensure that Employee entity cannot update the Department entity?
@Entity
public class Employee {
// ...
@ManyToOne(optional=false)
@JoinColumn(name="DEPT_ID", insertable=false, updatable=false)
private Department department;
// ...
}
Upvotes: 1
Views: 8692
Reputation: 47994
optional = false
on the ManyToOne is a runtime instruction for the persistence framework to interpret when building java objects. nullable = true
on the JoinColumn is for setting up the database schema and may or may not be interpreted at runtime depending on your persistence provider.
Normally that JoinColumn mapping is done that way to indicate that the relationship is managed from the other side, by the Department.
You would likely have:
@OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name="DEPT_ID")
private Set<Employee> employees;
Over on your department, and you'd create new employee-department relationships by adding them to the collection there, rather than setting a Department on the Employee. That's why you mark the Employee's department as non-updatable, because the Department "owns" the ability to modify the relationship.
Upvotes: 2