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

标签 java hibernate jpa

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

如果我使用@Transient,该字段将被完全忽略,这不是我想要的。有什么办法吗?

最佳答案

来自优秀的书 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.

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

关于java - JPA:在保存时忽略字段,但在选择时获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28485573/

相关文章:

java - SDK 管理器没有找到 java

java - 在 Spring MVC 中使用 Ajax 和 SimpleFormController

Spring Boot : The managed version is 1. 3.2.RELEASE Artifact 在 org.springframework.boot :spring-boot-dependencies:1. 3.2.RELEASE 中管理

java - Hibernate Restrictions.in() 只接受 propertyName 作为 String

java - 表中的更多名称属性

database - 玩耍、 hibernate 和进化

jakarta-ee - 过滤器不初始化 EntityManager

java - 如何使用mybatis在postgres中将int[]映射到integer[]

java - 为什么我不能正确检索数据?

java - Hibernate:按内部列表的值过滤实体的结果列表