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

有这样一个需求,根据姓名(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;
@Repository
public 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;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值