当依赖属性更改时如何在实体上设置 ModifiedDate
假设 JPA 实体 Foo
。通过添加注释,我可以处理 createdDate
和 modifiedDate
属性的更新。更改 name
并保留 Foo
后,createdDate
已正确更新。但这对于 bars
不起作用,它是 Bar
实体列表
@Entity
class Foo {
...
String name;
@OneToMany(cascade = CascadeType.PERSIST)
List<Bar> bars;
Date modifiedDate;
Date createdDate;
@PrePersist
public void updateCreatedDate() {
dateCreated = new Date();
}
@PreUpdate
public void updateModifiedDate() {
lastModified = new Date();
}
...
}
@Entity
class Bar {
...
}
如果 bars< 中的一个项目是否可以更新
Foo
/code> 更改并保留?
Assume the JPA-Entity Foo
. By adding annotations, i can handle updating the createdDate
and modifiedDate
properties. After changing name
and persisting Foo
, createdDate
is updated correctly. But this does not work for bars
which is a List of Bar
Entities
@Entity
class Foo {
...
String name;
@OneToMany(cascade = CascadeType.PERSIST)
List<Bar> bars;
Date modifiedDate;
Date createdDate;
@PrePersist
public void updateCreatedDate() {
dateCreated = new Date();
}
@PreUpdate
public void updateModifiedDate() {
lastModified = new Date();
}
...
}
@Entity
class Bar {
...
}
Is it possible to update Foo
if one Item in bars
changes and is persisted?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以封装对条形列表的每次修改,并在每次修改列表时将实体标记为脏(例如,通过将修改日期设置为另一个值):
请注意,这将生成更多查询,因为通常添加条形只需要在 bar 表中插入一个(如果使用连接表,则在连接表中也需要插入一个)。现在,每个栏的添加也会导致 Foo 表中的更新。
You might encapsulate every modification to the list of bars, and mark the entity as dirty (by setting the modification date to another value, for example) each time the list is modified:
Note that this will generate more queries, because adding a bar normally needs just one insert in the bar table (and one in the join table if a join table is used). Now every bar addition will also cause an update in the Foo table.