java JPA:在保存时忽略字段,但在选择时获取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28485573/
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 13:40:39  来源:igfitidea点击:

JPA: ignore field on save, but fetch on select

javahibernatejpa

提问by ba0708

I am using Hibernate as my JPA provider, and I want one of the fields in an entity to be ignored when calling save(). However, I do have a matching column in the corresponding database table and I want my entity field to be populated with the database value when I fetch the entity. So, I want the field to be ignored when saving the entity, but not when fetching it.

我使用 Hibernate 作为我的 JPA 提供程序,并且我希望在调用save(). 但是,我在相应的数据库表中有一个匹配的列,并且我希望在获取实体时用数据库值填充我的实体字段。所以,我希望在保存实体时忽略该字段,而不是在获取它时。

If I use @Transient, the field is completely ignored, which is not what I want. Is there any way to do this?

如果我使用@Transient,该字段将被完全忽略,这不是我想要的。有没有办法做到这一点?

回答by Lukas Risko

From the excellent book Pro JPA 2:

从优秀的书Pro JPA 2

JPA defines options to set individual mappings to be read-only using the insertable and updatable elements of the @Column and @JoinColumn annotations. These two settings default to true but can be set to false if we want to ensure that the provider will not insert or update information in the table in response to changes in the entity instance. If the data in the mapped table already exists and we want to ensure that it will not be modified at runtime, then the insertable and updatable elements can be set to false, effectively preventing the provider from doing anything other than reading the entity from the database.

JPA 定义了使用@Column 和@JoinColumn 注释的可插入和可更新元素将单个映射设置为只读的选项。这两个设置默认为 true 但如果我们要确保提供程序不会插入或更新表中的信息以响应实体实例中的更改,则可以将其设置为 false。如果映射表中的数据已经存在,并且我们要保证在运行时不会被修改,那么可以将insertable和updatable元素设置为false,有效防止provider除了从数据库中读取实体外做任何事情.

@Column(insertable = false, updatable = false)
private String readOnlyField;