开发者

Best practice to return a result Flag after saveOrUpdate in hibernate?

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 ?

Exception should be caught in DAO layer or Service Layer ?


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 ;
}

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;
  } 
}


Why you need to return anything here? If it happens to be unsuccessful, exception is there to tell you about that.

In case your calling method need something, you can just do it like this.

public void saveOrUpdateA(A a) throws Exception{
    // obtaining session is omitted
    session.saveOrUpdate(a);
}


The issue with the code is that you do not bubble up the exception. The rule we tend to follow is: If there is an exception, throw that up. If there is no exception, then it has completed successfully.


I dont think you should wrap this method at all. Just use it keeping in mind that you will have an exception in case of error.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜