java 使用 JPA 进行更新时如何排除实体字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28363625/
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
How to exclude an entity field when doing an update with JPA
提问by aurelius
Is there a way to make a field non-persistent at update operation but persistent at create operation with JPA - Hibernate 4?
有没有办法使字段在更新操作时非持久化,但在使用 JPA - Hibernate 4 创建操作时持久化?
I tried it in this way
我是这样试的
@Transient
@Id
@Column(name = "USER_NAME", nullable = false, length = 75)
private String userName;
but with @Transient annotation the field will be transient across all CRUD operations and I want a way to specify that only on this operation is persistent (create).
但是使用@Transient 注释,该字段在所有 CRUD 操作中都是瞬态的,我想要一种方法来指定仅在此操作上是持久的(创建)。
Is there a way to do this?
有没有办法做到这一点?
Thanks!
谢谢!
回答by Vlad Mihalcea
As explained in this article, you need to set updatable
to false
:
如本文所述,您需要设置updatable
为false
:
@Column(name = "USER_NAME", nullable = false, length = 75, updatable= false)
private String userName;
The updatable
attribute instruct Hibernate to omit this column from the generated UPDATE
SQL statement.
该updatable
属性指示 Hibernate 从生成的UPDATE
SQL 语句中省略此列。
I removed the @Transient
and the @Id
annotations.
我删除了@Transient
和@Id
注释。
If this column is your PK (mapped to the entity identifier), then you can only set it during INSERT, since Hibernate doesn't allow you to update an entity identifier (the updatable
attribute being redundant in this case).
如果此列是您的 PK(映射到实体标识符),那么您只能在 INSERT 期间设置它,因为 Hibernate 不允许您更新实体标识符(updatable
在这种情况下该属性是多余的)。