强制 JPA 从数据库重新加载实体 [英] Force JPA to reload entity from database
问题描述
我有一个 Foo
实体,它以一对一的关系链接到一个 Status
实体:
I have a Foo
entity that's linked to a Status
entity in a one-by-one relationship:
@Entity
@NamedQueries({
@NamedQuery(name = "Foo.findById", query = "select o from Foo o where o.fooId = :fooId")
})
public class Foo implements Serializable {
@Id
@Column(name="FOO_ID")
private Long fooId;
@OneToOne(mappedBy = "foo")
private Status status;
public Long getFooId() {
return fooId;
}
public void setFooId(Long fooId) {
this.fooId = fooId;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
}
@Entity
public class FooCurrentStatus implements Serializable {
@Id
private Long fooId;
@OneToOne
@JoinColumn(name = "FOO_ID")
private Foo foo;
public Long getFooId() {
return fooId;
}
public void setFooId(Long fooId) {
this.fooId = fooId;
}
public Foo getFoo() {
return foo;
}
public void setFoo(Foo foo) {
this.foo = foo;
if (foo != null) {
this.fooId = foo.getFooId();
}
}
}
我明白这并非完全错误,因为当我获取 Foo
实例时,我会自动获取其状态.
I understand this is not completely wrong because when I fetch a Foo
instance I automatically get its status.
从应用的角度来看,状态是只读的.它由其他一些修改数据库信息的无关进程在别处管理.
From the application point of view, the status is read-only. It is managed elsewhere, by some other unrelated process that modifies the database information.
不幸的是,副作用是每当状态发生变化时,我的托管实体就会过时.
Unfortunately, the side effect is that whenever the status changes my managed entity gets outdated.
如何指示 EJB/JPA 获取新状态?
How can I instruct EJB/JPA to grab a fresh status?
推荐答案
refresh()
专门用于此类用例,它可以强制刷新已从数据库加载实例的状态:
refresh()
on the EntityManager
API is particularly used for such use-case, which can force refreshing the state of an already loaded instance from the database:
entityManager.refresh(foo.getStatus());
这篇关于强制 JPA 从数据库重新加载实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!