实施“触摸"操作.在JPA实体上? [英] Implementing "touch" on JPA entity?

查看:30
本文介绍了实施“触摸"操作.在JPA实体上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我们的基础实体类(所有实体派生自)中,除其他外,我们有2种方法.一个带有@PrePersist的注释基本上设置了dateCreated,另一个带有@PreUpdate的注释设置了dateUpdated字段.

In our base entity class (that all entities derive from), we have, amongst others, 2 methods. One annotatted with @PrePersist which basically just sets the dateCreated, and the other annotated with @PreUpdate which sets the dateUpdated field.

这很完美,因为我们不希望在创建时设置dateUpdated字段.作为设计的一部分,我们还制作了两个方法protected,以便其他开发人员不要去明确地弄乱这两个日期(也没有设置方法).

This works perfectly, as we do not wish to set the dateUpdated field on creation. As part of the design, we also make the two methods protected so that other developers don't go and explicitly mess with those two dates (also no setters).

此外,通过在实际实体上定义方法并用@PrePersist对其进行注释,我们可以轻松地扩展任何实体以在创建时设置dateUpdated字段,因此将覆盖这一部分.

Also, we can easily enough extend any entity to set the dateUpdated field on creation by defining a method on the actual entity and also annotate it with @PrePersist, so this part is covered.

现在,我目前的问题是,在某些情况下,我们希望显式更新实体上的dateUpdated字段,而实体上的任何数据都不会更改(基本上是touch).有没有一种优雅的方法可以做到这一点?我真的不想实现一种方法,该方法可以更改其中一个字段,然后再将其更改回.而且,我们希望保留那些字段没有设置方法的实体.

Now, my problem at the moment is that there is a case where we would like to explicitly update the dateUpdated field on an entity, without any data on it changing (basically touch it). Is there an elegant way of doing this? I do not really want to implement a method that changes one of it's fields and then change it back. And we would like to keep having the entities without setter methods for those fields.

谢谢!

推荐答案

您是否尝试过仅更改dateUpdated字段值?我猜这应该使实体修改为Hibernate,并且Hibernate将调用@PreUpdate方法,该方法会将dateUpdated字段设置回当前时间:

Have you tried just changing the dateUpdated field value? I guess this should make the entity modified to Hibernate, and Hibernate would call the @PreUpdate method which would set the dateUpdated field back to the current time:

public void touch() {
    this.dateUpdated = -1;
}

这篇关于实施“触摸"操作.在JPA实体上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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