Hibernate / persistence有哪些常见问题? [英] what are some common problems with Hibernate/persistence?

查看:136
本文介绍了Hibernate / persistence有哪些常见问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,我想对可能与Hibernate和/或持久性相关的问题进行测试。

I have an application I'd like to test-proof against possible problems related to Hibernate and/or persistence.

还有什么其他问题?我如何重现它们(字面意思)?你是如何从中恢复过来的?

为了说清楚:我在谈论多线程集群环境(最复杂的一个) )。

我的一个:

org.hibernate.StaleObjectStateException :行已被另一个事务更新或删除(或未保存的值映射不正确)

重现:


  • 加载对象。

  • 使用HQL更新。

  • 尝试更新(保存)加载的对象。

句柄:不确定......

Handle: Not sure...

推荐答案

延迟加载是您将遇到的一个重大问题,特别是如果您遵循标准的DAO模式。你最终会得到延迟加载的集合,但是当你从DAO层出来时,spring(或者你没有使用spring的话)会关闭会话。

Lazy loading is one the big issues you'll encounter, especially if you follow a standard DAO pattern. You'll end up with lazy loaded collections, but upon coming out of your DAO layer, spring (or something else if you're not using spring) might close the session.

public class MyDaoImpl implements MyDao {
   @Override
   @Transactional
   public void save(MyObject object) { ... }
}

在这种情况下,当保存的调用完成时,如果你是,spring会关闭你的会话不属于另一个交易。因此,对延迟加载的对象的任何调用都将抛出LazyInitializationException。

In this case, when the call to "save" completes, spring will close your session if you are not within another transaction. As a result, any calls to lazily loaded objects will throw a LazyInitializationException.

处理此问题的典型方法是将会话绑定到当前线程。在webapps中,您可以使用OpenSessionInViewFilter轻松完成此操作。对于命令行,您可能需要编写一个实用程序方法来创建会话,绑定到当前线程,然后在完成后解除绑定。你可以在网上找到这方面的例子。

The typical way to handle this is to bind a session to the current thread. In webapps, you can do this easily with the OpenSessionInViewFilter. For command line, you'll probably need to write a utility method which creates a session, binds to the current thread, and then unbinds when you're done. You can find examples of this all over the web.

关于馆藏的主题,如果你使用更新方法(你通常会做的事情)一个标准的DAO模式),你必须小心不要替换集合实例,而是应该操作已经存在的集合。否则,hibernate将很难确定需要添加/删除/更新的内容。

And on the subject of collections, if you use the "update" method (again something you'd typically do with a standard DAO pattern), you have to be careful not to replace collection instances, but rather you should manipulate the collection that's already in place. Otherwise, hibernate will have a hard time figuring out what needs to be added/removed/updated.

这篇关于Hibernate / persistence有哪些常见问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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