如何使用JPA进行更新时排除实体字段 [英] How to exclude an entity field when doing an update with JPA

查看:523
本文介绍了如何使用JPA进行更新时排除实体字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在更新操作中使字段非持久化但在使用JPA创建操作时持久 - Hibernate 4?

Is there a way to make a field non-persistent at update operation but persistent at create operation with JPA - Hibernate 4?

我试过这样的方法

@Transient
@Id
@Column(name = "USER_NAME", nullable = false, length = 75)
private String userName;

但是对于@Transient注释,该字段在所有CRUD操作中都是暂时的,我想要一种方法来指定只有在这个操作上持久化(创建)。

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).

有没有办法做到这一点?

Is there a way to do this?

谢谢!

推荐答案

本文,您需要设置可更新 false

@Column(name = "USER_NAME", nullable = false, length = 75, updatable= false)
private String userName;

可更新属性指示Hibernate省略这个生成的 UPDATE SQL语句中的列。

The updatable attribute instruct Hibernate to omit this column from the generated UPDATE SQL statement.

我删除了 @Transient @Id 注释。

如果此列是您的PK(映射到实体标识符),那么您只能在INSERT期间设置它,因为Hibernate不允许您更新实体标识符(在这种情况下,可更新属性是多余的。)

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).

这篇关于如何使用JPA进行更新时排除实体字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆