利用hibernate执行jdbc中的事务处理

//此为更新的例子     
try{    
    Session session = HibernateUtil.currentSession();    
    try{    
        Connection connection = session.connection();// 获取连接    
        PreparedStatement preparedStatement = null;    
        String deleteSQL = "delete from a where b=c";    
        //开始事务    
        connection.setAutoCommit(false);            
        preparedStatement = connection.prepareStatement(deleteSQL);    
        preparedStatement.executeUpdate();    
        //提交JDBC事务    
        connection.commit();    
        // 恢复JDBC事务的默认提交方式    
        connection.setAutoCommit(true);    
        preparedStatement.close();    
    }catch (SQLException x) {    
        connection.rollback();    
        throw x;    
    }    
}catch(HibernateException e){    
   e.printStackTrace();    
            throw e;       
}finally{    
   HibernateUtil.closeSession();    
}    
     
//关于查询:    
try{    
    Session session = HibernateUtil.currentSession();    
    try{    
        Connection conn = session.connection();    
        PreparedStatement prepstmt = conn.prepareStatement(query);    
        prepstmt.setLong(1,Long.parseLong(paperId));    
        ResultSet rs = prepstmt.executeQuery();       
        ArrayList rsl = new ArrayList();    
        while(rs.next()){    
            HashMap item = new HashMap();    
            item.put("××",Long.toString(rs.getLong("××")));    
            rsl.add(item);        
        }        
        //一定要养成好习惯用完就关,否则会报“游标超出最大值”的错误的    
        rs.close();    
        prepstmt.close();    
    }catch (SQLException x) {    
        connection.rollback();    
        throw x;    
    }    
}catch(HibernateException e){    
   e.printStackTrace();    
            throw e;       
}finally{    
   HibernateUtil.closeSession();    
}    
   
//调用存储过程:    
try{    
    Session session = HibernateUtil.currentSession();    
    Connection conn = session.connection();        
    CallableStatement cstmt = conn.prepareCall("{call SAVE_AS_NEW_PAPER(?,?)}");    
    cstmt.setLong(1, new Long(newPid).longValue());         
    cstmt.setLong(2, new Long(oldPid).longValue());     
    cstmt.executeQuery();    
    cstmt.close();         
}catch(HibernateException e){    
    throw e;    
}catch(SQLException e){    
    throw e;    
}finally{    
    HibernateUtil.closeSession();    
}  

你可能感兴趣的:(C++,c,Hibernate,jdbc,C#)