我是否需要用 try-catch 包含所有 saveOrUpdate 方法?
我是否总是需要使用如下所示的 try-catch 块将 DAO 中 Session
上的 saveOrUpdate
或 delete
括起来?
public void save(Inventory object) {
try {
factory.getCurrentSession().saveOrUpdate(object);
} catch (Exception e) {
_logger.error("Cannot save or update object " + object, e);
}
}
Do I always need to enclose the saveOrUpdate
or delete
on Session
in DAOs with try-catch block like this bellow?
public void save(Inventory object) {
try {
factory.getCurrentSession().saveOrUpdate(object);
} catch (Exception e) {
_logger.error("Cannot save or update object " + object, e);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一般来说,这取决于您是否想要在 DAO 中处理特定的异常。但请注意,在您的具体示例中,会话可能不会被刷新,因此您无论如何都不会得到任何有趣的异常(例如约束违规)。所以我想说,捕捉它们比允许它们传播更有意义。但没有硬性规定。
Generally it depends on whether you want to handle specific exception in your DAO or not. But note, that in your specific example, session may not be flushed and as a result you will not get any interesting exceptions (like constraint violation) anyway. So I'd say it makes less sense to catch them than to allow them to propagate. But there is no firm rule.
org.hibernate.Session.saveOrUpdate 抛出 HibernateException,所以是的,捕获异常可能是个好主意。但我建议如果可以的话,在 try/catch 块中执行整个事务,以便在失败时可以将其回滚。以下是执行此操作的常见习惯用法:
您可以找到更多信息 这里更一般地介绍hibernate 这里。
org.hibernate.Session.saveOrUpdate throws HibernateException, so yes, it's probably a good idea to catch the exception. But I'd recommend doing your entire transaction in a try/catch block if you can so that you can roll it back if it fails. Here's a common idiom for doing this:
You can find more information here and more generally about hibernate here.
您可以使用几种模式。
最简单的方法是仅声明
throws Exception
,但抛出Exception
是一个非常糟糕的设计选择 - 它太高级了。事实上,问题在于 Hibernate - 它的方法应该声明为抛出比 Exception 更窄的内容。更好的方法是:
MyDatabaseException
像这样:
第二种方法是常用的图案。
PS 如果你将此与 @Seth 的 try-catch-finally 好主意结合起来,你会得到一个更好的方法。
There are a couple of patterns you could use.
The simplest is to just declare
throws Exception
, but throwingException
is a very poor design choice - it's way too high-level. In fact, the villan is Hibernate - its methods should be declared as throwing something more narrow thanException
.A better way is to:
MyDatabaseException
Like this:
This second approach is a commonly used pattern.
P.S. If you combine this with @Seth's good idea of try-catch-finally, you'd get an even better approach.
我们的设计是让处理异常的业务逻辑代码执行 try 并捕获异常,因为它会知道是否需要重试以及下一步要做什么。 DAO 类将捕获所有异常并抛出给业务逻辑代码,从而仅专注于数据库增删改查部分。所以 DAO 类将来总是可以重用的。
Our design is to let the business logic code that handle do the try and catch exception because it would know if it need to retry or not and what to do next. The DAO class will catch all exception and throw to the business logic code thereby only concentrate on database crud part. So the DAO classes will always be reusable in the future.