入离职管理系统——如何实现多条件查询

来源:互联网 发布:航天数据股份有限公司 编辑:程序博客网 时间:2024/06/10 19:05

有这样一个需求,根据姓名(fullname)、职位(position)、状态(status)中的一个或者多个条件,查询新员工信息。这里的问题在于,用户在查询时,可能只输入了fullname一个条件,这样我们就不能简单的将hql语句写成下面这样:

String hql = "from StaffVo as s where s.fullname = :fullname and s.position = :position and status = :status";

为了满足需求,可以写成下面这样,关键点在于使用了StringBuffer的append(String str)方法,拼接hql语句:

package com.entry_exit.dao.impl;import java.util.Iterator;import java.util.List;import org.springframework.stereotype.Repository;import com.entry_exit.dao.StaffDao;import com.entry_exit.vo.StaffVo;@Repositorypublic class StaffDaoImpl extends BasicDaoImpl<StaffVo> implements StaffDao {    @Override    public List<StaffVo> queryWithConditions(String fullname, String position, String status, int page, int rows) {        // TODO Auto-generated method stub        System.out.println("进入dao方法");        //String hql = "from StaffVo as s where s.fullname = :fullname and s.position.id = :position and status = :status";        StringBuffer hql1 = new StringBuffer();         hql1.append("from StaffVo where ");         if(fullname != null && fullname.length() > 0){             hql1.append("fullname like '%");             hql1.append(fullname);             hql1.append("%' and ");         }         if(position != null && position.length() > 0){             hql1.append("position.position = '");             hql1.append(position);             hql1.append("' and ");         }         if(status != null && status.length() > 0){             hql1.append("status = '");             hql1.append(status);             hql1.append("' and ");         }         //去除多出来的“' and ”,并返回字符串         String hql = hql1.substring(0, hql1.length()-5);        //List<StaffVo> staffList = getSession().createQuery(sql).setString("fullname", fullname).setString("status", status).setFirstResult((page-1)*rows).setMaxResults(rows).list();         List<StaffVo> staffList = getSession().createQuery(hql).setFirstResult((page-1)*rows).setMaxResults(rows).list();         if(!staffList.isEmpty()){            Iterator<StaffVo> it = staffList.iterator();            System.out.println("查询到的结果如下:");            while(it.hasNext()){                System.out.println(it.next().getStaffid());            }        }        return staffList;    }}
原创粉丝点击