Hibernate对数据库进行更新删除及service层调用的处理

本文介绍了使用Java进行数据库持久层操作的方法,包括保存和删除记录的具体实现,并展示了如何通过异常处理来确保事务的正确性。
 public boolean save(TpTitempRel transientInstance) {
     boolean returnValue=true;
     Transaction tr = null;
        try {
         tr = getSession().beginTransaction();
            getSession().save(transientInstance);
            tr.commit();
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            tr.rollback();
            returnValue=false;
            throw re;  
        }finally{
         this.closeSession();
        }
       return returnValue;
    }
    
 public void delete(String procode) {
        log.debug("deleting TpTitempRel instance");
        Session session = this.getSession();
        try {
         String hql ="delete from T_Titemp_Rel where product_code='"+procode+"'";
            session.createSQLQuery(hql).executeUpdate();
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }

在Service调用:

if (xx.save(ttr)) {
      //........

 }

如果不抛异常,save()返回true,就继续执行,否则,会抛异常,不会执行if

 

----------------------------------------------------------------------------------------------------

public class Test {

 /**
  * @param args
  * @throws Exception 
  */
 public static void main(String[] args) throws Exception {
  
  System.out.println(Test.test());


 }
 
 public static boolean test(){
  boolean flag = true;
  System.out.println("Hello World!!!"); 
     try{ 
      //System.out.println(1/0); //第一种情况

      System.out.println(1/1); //第二种情况

      flag = false;
     }catch(ArithmeticException e){ 
      System.out.println("除数为0!"); 
      throw e;
     } 
     return flag;
 }

}

执行结果:

//第一种情况

Hello World!!!
Exception in thread "main" java.lang.ArithmeticException: / by zero
 at test.Test.test(Test.java:46)
 at test.Test.main(Test.java:37)
除数为0!

注意:有异常的时候,就不会走后面的return语句啦!

//第二种情况
Hello World!!!
1
false

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值