如何使用jpa/spring-boot正确应用PrePersist之类的逻辑 [英] How to properly apply PrePersist like logic using jpa/spring-boot
问题描述
对于以下模型,我有一个非常简单的用例
I have a very simple use case for the following model
@Entity
@Table(name='Foo')
class Foo {
@Id
String id = UUID.randomUUID()
String bar
Date foo_updated
}
当我看到传入的json有效负载具有"bar"的值时,我想将foo_updated值设置为new Date()(即-这是POST中包含的新值/PATCH更新的一部分) /包含在内,并证明在PUT中与众不同)
I'd like to set the foo_updated value to new Date() when I see the incoming json payload has a value for "bar" (ie- this is a new value included in the POST/ a part of the PATCH update / included and proven to be different in a PUT)
我希望在此模型上简单地应用@PrePersist批注,并添加一个简单的条件询问"bar"是否有效...但很快意识到我不知道该值是否与其中的值不同"数据库(对于PATCH/PUT场景).
I was hoping to simply apply the @PrePersist annotation on this model and add a simple conditional asking if "bar" was valid ...but quickly realized I wouldn't know if the value was "different" from what was in the db already (for the PATCH/PUT scenario).
我正在开始添加我自己的RestController",并在使用spring 4 ResponseEntity方法的过程中应用此逻辑,但是...我觉得这可能最终会花费更多的工作/更多的代码保持.
I'm starting down the road of "add my own RestController" and apply this logic on the way in using the spring 4 ResponseEntity approach but ... I feel this might end up being a lot more work/more code to maintain.
当我是spring-boot/spring-mvc/jpa的新手时,我很好奇我还有什么其他选择,并且对于这种看似简单"的要求,首选的方法是什么
As I'm new to spring-boot/spring-mvc/jpa I'm curious what other options I have and what the preferred approach would be for this seemingly "simple" requirement
感谢您的帮助!
推荐答案
我最近遇到了这种方法,该方法涉及记录加载时的先前状态.新值绑定后,您现在可以访问以前的状态.
I came across this approach recently which involves recording the previous state on load. You now have access to the previous state after the new values are bound.
@Entity
@Table(name='Foo')
class Foo {
@Id
String id = UUID.randomUUID()
String bar
Date foo_updated
@Transient
private Foo previousState;
@PostLoad
private void setPreviousState(){
previousState = new Foo();
//copy the fields
}
}
但是,就您而言,您不能这样做:
However in your case can't you just do:
@Entity
@Table(name='Foo')
class Foo {
@Id
private String id = UUID.randomUUID()
private String bar
private Date lastUpdated;
public void setBar(String bar){
if(! this.bar.equals(bar){
lastUpdated = new Date();
}
}
}
这篇关于如何使用jpa/spring-boot正确应用PrePersist之类的逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!