zoukankan      html  css  js  c++  java
  • hibernate通过SQL更新数据

     1     @Resource(name = "hibernateTemplate")
     2     public HibernateTemplate hibernateTemplate;
     3     
     4     /**
     5      * @Title: updateBySQL
     6      * @Description: TODO(sql更新)
     7      * @param @param sql sql语句
     8      * @param @param obj 参数
     9      * @param @return
    10      * @return int 更新数量
    11      * @throws
    12      */
    13     public int updateBySQL(final String sql, final Object[] obj) {
    14         return hibernateTemplate.execute(new HibernateCallback() {
    15             public Object doInHibernate(Session session)
    16                     throws HibernateException, SQLException {
    17                 SQLQuery query = session.createSQLQuery(sql);
    18                 if (obj != null && obj.length > 0) {
    19                     for (int i = 0; i < obj.length; i++) {
    20                         query.setParameter(i, obj[i]);
    21                     }
    22                 }
    23                 return query.executeUpdate();
    24             }
    25         });
    26     }
    1     /**
    2      * 添加测试
    3      */
    4     public void addTest() {
    5         String sql = "insert test values(?, ?)";
    6         int i = this.updateBySQL(sql, new Object[]{1, "test1"});
    7         System.out.println("更新记录数:"+i);
    8     }

    运行结果:

     

    数据库:

     

    注:我是在项目直接测试的,

    1. hibernateTemplate通过spring注入。

    2. addTest通过junit进行测试的。

  • 相关阅读:
    算法
    如果业界中不用高级算法和数据结构,那为什么还要学?
    CentOS 7 运行级别切换
    ECharts笔记
    Vue+TypeScript学习
    TypeScript深入学习
    TypeScript基础
    检测数据类型的方法
    前端提高性能的方式
    柯里化
  • 原文地址:https://www.cnblogs.com/frank-quan/p/4260947.html
Copyright © 2011-2022 走看看