Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA readonly mapping

Tags:

java

jpa

Toplink can use read-only mappings when multiple attributes in an object map to the same fields in the database but only one of the mappings can write to the field.

Does JPA has such feature, how to write annotation? I have one @ManyToOne and one @Column annotation which need to map to same field in database.

@ManyToOne(optional=false, fetch=FetchType.LAZY)
@JoinColumn(name="USR_ID", referencedColumnName="USER_ID", nullable=false)
private User user;
    
/** @generated **/
@Column(name="USER_ID", nullable=false, length=30)
private String userId;
like image 637
Jackie Dong Avatar asked May 07 '15 02:05

Jackie Dong


People also ask

How do I make my entity class read-only?

Entities of immutable classes are automatically loaded as read-only. To change the default behavior so Hibernate loads entity instances of mutable classes into the session and automatically makes them read-only, call: Session. setDefaultReadOnly( true );


1 Answers

From here

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.

So

    @Column(name="USER_ID", nullable=false, length=30,
        updatable=false, insertable=false)
    private String userId;

should do it

like image 175
Raniz Avatar answered Sep 28 '22 08:09

Raniz