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進行測試的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM