开发者

What is the best way to compare a persistent or detached hibernate object with it's current DB state?

I'm using Hibernate and Spring.

I'm writing a service method to save an object (a charge) that has very specific business rules about when it's allowed to be saved based on it's current DB state. For example,开发者_如何转开发 if charge.status.equals(Status.CANCELED) it should not be updated. (There are other more specific rules, but that should be a good example to work with) It's possible that other code could load a canceled charge and erroneously change the status to approved and then call save(charge). The save method needs to be able to identify this error whether the charge that was passed in is persistent or detached.

Is there an easy way to compare the object I have in memory with the current persistent state of the object in the DB?


I think this will work:


public void save(Charge charge) {
    Session session = sessionFactory.getCurrentSession();
    Charge copy = new Charge(charge);
    session.refresh(charge);
    ...
    //various business logic checks between copy and charge
    ...
    session.saveOrUpdate(charge);
}

I would certainly appreciate any advice if this is flawed or if there is a better way.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜