Read-only association with JPA OneToMany mapping
You can add updatable=false
on @JoinColumn annotation.
Furthermore you should not add a setter method for user
in your Case
entity and same for caseSet
in your User
entity. The getter getCaseSet
in User
entity should also return an unmodifiable collection:
public Set<Case> getCaseSet() {
return Collections.unmodifiableSet(caseSet);
}
The Column annotation and XML element defines insertable and updatable options. These allow for this column, or foreign key field to be omitted from the SQL INSERT or UPDATE statement. These can be used if constraints on the table prevent insert or update operations. They can also be used if multiple attributes map to the same database column, such as with a foreign key field through a ManyToOne and Id or Basic mapping. Setting both insertable and updatable to false, effectively mark the attribute as read-only.
In @OneToMany
mapping, @JoinColumn
annotation, add both updatable=false
and insertable=false
, then specify the cascade type as PERSIST instead of ALL
@OneToMany(cascade = CascadeType.PERSIST)
@JoinColumn(name = "<ReadOnlyTableName>", updatable = false, insertable = false)