在休眠状态下的saveOrUpdate之后返回结果标志的最佳实践? [英] Best practice to return a result Flag after saveOrUpdate in hibernate?

查看:86
本文介绍了在休眠状态下的saveOrUpdate之后返回结果标志的最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,我们不得不使用一些不会返回任何有用信息的方法.如果我在休眠状态下调用saveOrUpdate(),则不知道它是否已成功执行. 我使用这样的实现(我觉得有点尴尬):

Often we have to use some of the methods which don't return anything useful. If I invoke saveOrUpdate() in hibernate , I don't know whether it has been performed successfully . I use a implementation like this (which I think is a bit awkward) :

public int saveOrUpdateA(A a) {
        int resultFlag = 0 ;
    try {
        // obtaining session is omitted
        session.saveOrUpdate(a);
        resultFlag = 1 ;    
    } catch (Exception e) {
        e.printStackTrace();
    } 
    return resultFlag ;
}

您如何做到这一点?有什么好主意吗?

How do you do this ? Any good idea ?

应该在DAO层或服务层中捕获异常吗?

推荐答案

缺少异常是成功的指示.

The lack of an exception is a success indicator.

如果您真的想要指标,我将获得布尔值回报.

If you truly want the indicator, I'd go for a boolean return.

public boolean saveOrUpdateA(A a) {
  boolean success = false;   
  try {
    // obtaining session is omitted
    session.saveOrUpdate(a);
    success = true;

  } catch (Exception e) {
    // log it and swallow exception
    // calling code has to be sure to check on success flag; 
    // otherwise it has no idea something went terribly wrong
  } 
  return success ;
}

您的应用程序仍然必须检查返回状态并适当地处理它,这与处理session.saveOrUpdate()引发的潜在异常没有太大区别.

Your application will still have to check the return status and handle it appropriately, which is not a whole lot different than handling the potential exception thrown by session.saveOrUpdate().

public void saveOrUpdateA(A a) throws Exception {

  try {
    // obtaining session is omitted
    session.saveOrUpdate(a);
  } catch (Exception e) {
    // log it and rethrow; let calling code figure how to handle
    throw e;
  } 
}

这篇关于在休眠状态下的saveOrUpdate之后返回结果标志的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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