Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read-only association with JPA OneToMany mapping

I have a transactional entity associated to another entity whereby the associated should not be updated in an case.

Eg. Case *-> User

Where a Case is owned by a User and reversely a User can have many associated Case.

The association is mapped using OneToMany and JoinColumn JPA annotations.

I have also tried marking the Trasactional annotation for User entity as readonly and also made the fetch methods Transient. But this doesnot seem to stop update on User if its state is changed.

Please help me a figure a way to declare a "read-only" association to User.

like image 419
anthos Avatar asked Feb 06 '11 09:02

anthos


2 Answers

You can add updatable=falseon @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);
}
like image 132
lweller Avatar answered Nov 03 '22 08:11

lweller


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)
like image 22
Mohammed Safeer Avatar answered Nov 03 '22 10:11

Mohammed Safeer