Hibernate:检查哪些实体的字段被修改 [英] Hibernate: check which entity's fields are modified

查看:20
本文介绍了Hibernate:检查哪些实体的字段被修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有什么:

我有 Hibernate 实体,其中包含许多非瞬态字段,包​​括集合.用户可以单独更新每个字段或一次更新某些字段组.

I've Hibernate entity, which contains many non-transient fields, including collections. User can update each field separately or some group of fields at once.

真是一个挑战:

在处理程序中,我应该检查实体的哪个字段已更改:

In handler I should check what field of the entity have been changed:

public void handle(Entity newVersion) {
  Session session = sessionFactory.openSession();
  Entity oldVersion = (Entity) session.get(Entity.class, entity.getId());
  List changedFields = compareChanges(oldVersion, newVersion);  //HOW TO CHECK WHICH FIELDS ARE CHANGED?
}

出于安全和通知原因,我想这样做.意思是:

I want to do it for security and notification reasons. Means:

  1. 并非所有用户都可以修改所有字段
  2. 对于某些字段的更改,我应该以特定方式通知特定用户.

有什么问题:

我得到了非常难看的代码.实际上我遍历所有字段/集合并调用 equals 方法.

I get very ugly code. Actually I iterate throught all fields/collections and call equals method.

问题:

Hibernate 可能提供更优雅的方式来检查哪些字段已被修改?怎么样?

P.S.

@victorantunes 提供了一个解决方案,但对我来说似乎太全面了.可能有一些替代方案?

@victorantunes provide a solution, but it seems too comprehensive for me. May be some alternatives?

推荐答案

您可以做的是制作一个 Hibernate Interceptor,它在创建、修改和更新等事件中充当触发器.http://docs.jboss.org/hibernate/orm/3.3/reference/zh/html/events.html以便在给定实体之前的任何点即将被修改和持久化,1.您可以检查用户是否具有修改特定字段的访问权限(您可以从会话或数据库中获取用户名),并相应地授予访问权限以进行保存或更新.2.只有在实体被修改时才能通知其他用户.

What you can do is make a Hibernate Interceptor that would act like a trigger in the events like create, modify and update. http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/events.html so that any point before the given entity is about to be modified and persisted, 1.You can check whether the user has the access (you can get username from session or database) to modify the particular field and accordingly you can grant the access to save or update. 2.You can notify the other user about only when the entity is modified.

通过这种方式你可以在 Spring 的 Hibernate 4 实现中创建一个新的 session-scope Interceptor会话会话 = s.withOptions().interceptor(new YourInterceptor().openSession();

By this way you can make a new session-scope Interceptor in spring's implementation ofHibernate 4 Session session = s.withOptions().interceptor(new YourInterceptor().openSession();

这篇关于Hibernate:检查哪些实体的字段被修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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