本文介绍了如何仅用Hibernate更新所有实体属性的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到了30个字段的JSON,而我的实体是由此JSON构建的。
问题是:两个字段不应该更新(两个日期)。

如果我使用 entity.merge

如何避免这两个字段被更新?



也许使用标准。例子?



有没有一些方法可以在没有我编写大量HQL的情况下做到这一点?

解决方案

详细解释了你的问题,但我也要在这里总结一下。



如果你永远不想更新这两个字段,你可以用 updatable = false 标记它们:

  @Column(name =CREATED_ON,updatable = false)
私人日期createdOn;

一旦你加载一个实体并修改它,只要当前 Session EntityManager 是开放的,Hibernate可以通过。然后,在刷新期间, SQL 更新将被执行。



如果您不喜欢所有列都包含在 UPDATE 语句,您可以使用动态更新:

  @Entity 
@DynamicUpdate
public class Product {
//为了简洁省略代码
}

然后,只有修改过的列将被包含在 UPDATE 语句中。


I receive a JSON with 30 fields, and my entity is built from this JSON.The problem is: two fields shouldn't be updated (two dates).

If I use entity.merge, both fields will be updated.

How can I avoid that those 2 fields get updated?

Maybe using criterion.Example?

Is there some way to do this without me writing a ton of HQL?

解决方案

This article explains in great details your question, but I'm going to summarize it here as well.

If you never want to update those two fields, you can mark them with updatable=false:

@Column(name="CREATED_ON", updatable=false)
private Date createdOn;

Once you load an entity and you modify it, as long as the current Session or EntityManager is open, Hibernate can track changes through the dirty checking mechanism. Then, during flush, an SQL update will be executed.

If you don't like that all columns are included in the UPDATE statement, you can use dynamic update:

@Entity
@DynamicUpdate
public class Product {
   //code omitted for brevity
}

Then, only the modified columns will be included in the UPDATE statement.

这篇关于如何仅用Hibernate更新所有实体属性的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 13:46