入離職管理系統——如何實現多條件查詢

有這樣一個需求,根據姓名(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;
    }

}
發佈了26 篇原創文章 · 獲贊 8 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章