hibernate批量更新和批量删除的方法有很多。下面举例:

方法一:hql方法。

[java] view plain copy
 
  1. /** 
  2.   * 更新内容数据,本次更新最新标志.条件是超过7天的数据 
  3.   * @return 更新的条数 
  4.   */  
  5.  public int updateContent() {  
  6.   Object[] params = {0, 1, new Date()};  
  7.  StringBuilder updateBuffer = new StringBuilder();     
  8.  updateBuffer.append("UPDATE TblContent SET ");     
  9.  updateBuffer.append("CIsElink=?");   
  10.  updateBuffer.append(",screenDate=?");   
  11.  updateBuffer.append("WHERE CIsElink=?");     
  12.  Type[]types = new Type[3];     
  13.  types[0] = Hibernate.INTEGER;     
  14.  types[2] = Hibernate.INTEGER;     
  15.  types[1] = Hibernate.TIMESTAMP;       
  16.    
  17.  try {     
  18.      Query query = getSession().createQuery(updateBuffer.toString());     
  19.      query.setParameters(params, types);     
  20.      int count = query.executeUpdate();    
  21.      //log.info(count+" has been batchUpdated successful!");     
  22.      return count;  
  23.      //this.commit();     
  24.  } catch (HibernateException e) {     
  25.      //this.rollback();     
  26.      //log.error("batchUpdate failed", e);     
  27.      throw e;     
  28.  }    
  29.   }  

方法二:jdbc api方法(预处理语句)。

 

 

[c-sharp] view plain copy
 
  1. public void updateContact(String oldUserId, String newUserId)  
  2.             throws HibernateException, SQLException {  
  3.         Session session = getSession();  
  4.         Transaction transcation = session.beginTransaction();  
  5.         Connection con = session.connection();  
  6.         StringBuffer sql = new StringBuffer("update TblContent set userId='")  
  7.                 .append(newUserId).append("'").append(" where userId='")  
  8.                 .append(oldUserId).append("'");  
  9.         PreparedStatement stmt = con.prepareStatement(sql.toString());  
  10.         stmt.executeUpdate();  
  11.         transcation.commit();  
  12.         session.close();  
  13.     }  

 

 
 

posted on 2017-07-10 14:38  alex5211314  阅读(377)  评论(0编辑  收藏  举报

导航