简体   繁体   中英

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.

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)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM