开发者

Refresh Hibernate Formula

开发者 https://www.devze.com 2023-02-19 17:57 出处:网络
I have got two entities (example reduced as much as possible; each entity has got an id field): @Entity

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 hap开发者_如何学编程pens 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();


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.


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 Xes 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消