刷新休眠公式
我有两个实体(示例尽可能减少;每个实体都有一个 id 字段):
@Entity
public class A {
@Column(nullable = false)
private double foo;
@Formula(value = "foo - (select coalesce(sum(x.foo), 0) from x where x.a_id = id)")
private double bar;
}
当
@Entity
public class X {
@ManyToOne(optional = false)
private A a;
@Column(nullable = false)
private double foo;
}
我创建一个新的 X
(new X()
, < code>beginTransaction()、save(x)
、commit()
) A.bar 的值未刷新。
我认为发生这种情况是因为旧的(且错误的)值仍在一级缓存中(没有二级缓存)。我不想调用 Session.clear() ,因为此方法似乎会使现有实体对象无效。我还能做什么来解决这个问题?
编辑:按照此处的要求,保存X
-对象的代码:
// setters
getSession().beginTransaction(); // getSession() returns the current session
getSession().save(entity); // entity is an instance of X
getSession().getTransaction().commit();
I have got two entities (example reduced as much as possible; each entity has got an id field):
@Entity
public class A {
@Column(nullable = false)
private double foo;
@Formula(value = "foo - (select coalesce(sum(x.foo), 0) from x where x.a_id = id)")
private double bar;
}
and
@Entity
public class X {
@ManyToOne(optional = false)
private A a;
@Column(nullable = false)
private double foo;
}
When I create a new X
(new X()
, beginTransaction()
, save(x)
, commit()
) the value of A.bar is not refreshed.
I think this happens because the old (and wrong) value is still in the first level cache (there is no 2nd level cache). I dont want to call Session.clear()
since this method seems to invalidate existing entity-objects. What else can I do to solve this probelm?
EDIT: As requested here is the code to save X
-objects:
// setters
getSession().beginTransaction(); // getSession() returns the current session
getSession().save(entity); // entity is an instance of X
getSession().getTransaction().commit();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Session.clear 将从会话中删除所有缓存的对象。相反,您可以在会话上使用 evict 方法并指定一个对象,这只会从缓存中删除指定的对象。
Session.clear will remove all the cached objects from the session. instead you can use evict method on session and specify an object, which removes only the specified object from the cache.
我尝试通过清除缓存来解决问题,但随之而来的是新问题,并使缓存或多或少变得毫无用处,因为
X
经常更改。 (事实上,子选择比问题中显示的要复杂得多。它使用更多的表。)现在我使用没有一级缓存的
StatelessSession
。这解决了问题。由于数据库是嵌入式 h2 数据库,因此性能下降并不明显。I tried to solve the problem with clearing the cache but that was followed up by new problems and made the cache more or less useless because
X
es are changed quite often. (In fact the subselect is much more complex than shown in the question. It uses more tables.)Now I am using the
StatelessSession
that does not have a first-level cache. This solves the problem. Since the database is an embedded h2-Database the performance regression is not noticeable.