070807 HibernateTemplate删除数据小结

删除
DAO代码:
 public void delete(Integer lid) {
        log.debug("deleting Login instance");
        try {
         Login login=(Login)this.getHibernateTemplate().load(Login.class,lid);
            getHibernateTemplate().delete(login);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }

调用DAO:
Integer selid = Integer.valueOf(request.getParameter("select"));
loginDAO.delete(selid);

批量删除
需要注意的是in后面跟的是字符串,如果不是会提示org.hibernate.QueryException: unexpected char: ';'的出错
DAO代码:
public void delete(String[] lid) {
    String[] ids = lid;
         String str="";
         for(int i=0;i<ids.length;i++){
             str+="'"+ids[i]+"'";
             if(i!=(ids.length-1))
                 str+=",";
             }
  List list   =   this.getHibernateTemplate().find("from Login where id in ("+str+")");
  if(list.size()>0){  
     this.getHibernateTemplate().deleteAll(list);
     }
 }

调用DAO:
String[] lid = request.getParameterValues("select");
loginDAO.delete(lid);

你可能感兴趣的:(DAO,Hibernate)