java JPA 只读映射

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30090941/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 16:27:19  来源:igfitidea点击:

JPA readonly mapping

javajpa

提问by Hymanie Dong

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.

当对象中的多个属性映射到数据库中的相同字段但只有一个映射可以写入该字段时,Toplink 可以使用只读映射。

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.

JPA有这个功能,注解怎么写?我有一个@ManyToOne 和一个@Column 注释,它们需要映射到数据库中的同一字段。

    @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;

回答by Raniz

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.

列注释和 XML 元素定义了可插入和可更新选项。这些允许从 SQL INSERT 或 UPDATE 语句中省略此列或外键字段。如果表上的约束阻止插入或更新操作,则可以使用这些。如果多个属性映射到同一数据库列,也可以使用它们,例如通过 ManyToOne 和 Id 或 Basic 映射使用外键字段。将可插入和可更新都设置为 false,有效地将该属性标记为只读。

So

所以

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

should do it

应该做