gpt4 book ai didi

java - hibernate 拦截器 : How do I override onCollectionUpdate and onCollectionRecreate to not populate my entities with database values?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:16:33 25 4
gpt4 key购买 nike

我正在扩展 org.hibernate.EmptyInterceptor 来解密和加密字段。目标是始终让内存中的域对象处于解密状态,并始终让存储的数据库值处于加密状态。

我已经覆盖了 EmptyInterceptor 的 preFlush 和 postFlush 方法。 preFlush 加密对象的字段,postFlush 解密对象的字段。每当 Hibernate 刷新一个对象时,这些字段都会以加密状态保存到数据库中。我可以在未加密状态下继续访问内存中对象的字段。我的 preFlush 和 postFlush 方法对我来说效果很好。

在很多情况下,我的应用程序需要加载已保存到数据库中的对象。我已经覆盖了 EmptyInterceptor 的 onLoad 方法来解密数据库中的值。加载的对象在调用 onLoad 后处于解密状态。但是,每当 Hibernate 执行不相关的查询时,我的内存中对象就会从数据库中提取加密值。我留下了一个无法使用的处于加密状态的内存中对象。

我怀疑我可以覆盖 EmptyInterceptor 的 onCollectionUpdate 和 onCollectionRecreate,这样 hibernate 将停止使用数据库中的值更新我的更新。我尝试在 onCollectionUpdate 和 onCollectionRecreate 中将集合参数设置为 null,但问题仍然存在。

关于如何阻止 hibernate 对数据库中需要加密的对象执行集合更新和重新创建有什么想法吗?

下面是我的 CryptoInterceptor 类的一个片段。我包含了当前的 onCollectionRecreate 方法,该方法将集合参数设置为 null。我的 onCollectionUpdate 方法类似。

public class CryptoInterceptor extends EmptyInterceptor
{

public static final Set<Class> CRYPTO_CLASSES = Collections.unmodifiableSet(new HashSet<Class>(Arrays.asList(new Class[]
{ User.class, Order.class, Account.class})));

@Override
public void onCollectionRecreate(Object aCollection, Serializable aKey) throws CallbackException
{
PersistentCollection persistentColl = (PersistentCollection)aCollection;

Object aEntity = null;

aEntity = persistentColl.getOwner();

if (aEntity == null)
{
return;
}

try
{
Class clazz = Class.forName(aEntity.getClass().getName());

if (!CRYPTO_CLASSES.contains(clazz))
{
return;
}
else
{
aCollection = null;
}
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}

return;
}
}

我从调试中知道,Hibernate 总是传入一个对象,该对象实现了集合对象的 org.hibernate.collection.PersistentCollection 接口(interface)。

最佳答案

我知道为时已晚,但由于我发现这篇文章可用作加密指南,所以我会指出您无法设置

 aCollection = null;

在函数内部,因为集合是一个参数,所以只是对对象的引用。如果你真的想这样做,你应该做类似的事情

aCollection.clear();

关于java - hibernate 拦截器 : How do I override onCollectionUpdate and onCollectionRecreate to not populate my entities with database values?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6443689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com