hibernate执行原生sql(直连jdbc解决)

来源:互联网 发布:faking it 编辑:程序博客网 时间:2024/06/08 16:22

使用hibernate执行原生sql时,使用connection过时的解决方法:

查了很多,此处暂时用了直连jdbc的方法来获取连接并执行sql语句(此处的session时通过BaseDao获取的,详细方法省去)。

public boolean executeSql(String sql){
        boolean result = false;
        try{
            //开启session和事务
            Connection conn =((SessionImplementor)this.session).getJDBCContext().borrowConnection();
            Statement statement = conn.createStatement();
            statement.execute(sql);

            //提交
            result = true;
        }catch(Exception e){
            //回滚
            e.printStackTrace();
        }finally{
           //关闭session
        }
        return result;
    }

注:sql语句最后一定不能加分号,否则会抛出异常

0 0
原创粉丝点击