休眠,保存一个对象的以前的状态 [英] Hibernate, save the previous state of an object

查看:103
本文介绍了休眠,保存一个对象的以前的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何普遍接受的,经过验证的工作方式使用hibernate,它保留了数据库中实体更改的历史记录?



我们需要跟踪我们希望能够撤消对对象的更改。

我尝试使用hibernate的拦截器,但只有当对象的旧状态做 merge()。大多数情况下,我们会做 update() saveOrUpdate(),尽管...



我现在正在让Guice和Guice一起管理会话。

解决方案

我已经完成了使用拦截器(根据 EmptyInterceptor 创建我自己的拦截器)。我能够在onFlushDirty()中获得所有更改(合并,保存,保存更新和删除)。

EmptyInterceptor 我使用过:

  @Override 
public boolean onFlushDirty(Object object,Serializable id,
Object [] newValues,Object [] oldValues,String []属性,
类型[]类型)throws CallbackException {

@Override
public boolean onSave (Object object,Serializable id,Object [] newValues,
String [] properties,Type [] types)throws CallbackException {
$ b $ @Override
public void onDelete(Object object,序列化ID,Object [] newValues,
String []属性,Type []类型)抛出CallbackException {

在onFlushDirty()中我必须查询实体的前一个状态:

  Connection c = sessionFactory.getCurrentSession( )。连接(); 
Session session = sessionFactory.openSession(c);

BaseEntity newBaseEntity =(BaseEntity)对象;
BaseEntity oldBaseEntity =(BaseEntity)session.get(newBaseEntity.getClass(),newBaseEntity.getId());


Is there any generally accepted, proven-to-work way using hibernate, that keeps a history of an entitys changes in the database?

We need to keep track of quite some objects and we want to be able to undo changes to objects.

I tried using the interceptors of hibernate, but the old state of the object is only available when doing merge(). Mostly we do update() or saveOrUpdate() though...

I'm currently letting warp-persist together with Guice manage the session.

解决方案

I've done this with an Interceptor (creating my own based on EmptyInterceptor). I was able to get all changes (merge, save, saveOrUpdate and delete) in onFlushDirty().

The methods of EmptyInterceptor I used:

@Override
public boolean onFlushDirty(Object object, Serializable id,
    Object[] newValues, Object[] oldValues, String[] properties,
    Type[] types) throws CallbackException {

@Override
public boolean onSave(Object object, Serializable id, Object[] newValues,
    String[] properties, Type[] types) throws CallbackException {

@Override
public void onDelete(Object object, Serializable id, Object[] newValues,
    String[] properties, Type[] types) throws CallbackException {

In onFlushDirty() I had to query the previous state of the entity:

Connection c = sessionFactory.getCurrentSession().connection();
Session session = sessionFactory.openSession(c);

BaseEntity newBaseEntity = (BaseEntity) object;
BaseEntity oldBaseEntity = (BaseEntity) session.get(newBaseEntity.getClass(), newBaseEntity.getId());

这篇关于休眠,保存一个对象的以前的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆