Hibernate HQL like

package com.lixing.hr.dao.impl;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.lixing.hr.dao.ReportDAO;
import com.lixing.hr.model.Emp;
import com.lixing.hr.util.HibernateUtils;

public class ReportDAOImpl implements ReportDAO {
    private SessionFactory sf = HibernateUtils.getSessionFactory();

    public List<Emp> query(String employNo, String employName, int deptId) {
        String employNoStr = "FROM Emp e WHERE e.employNo LIKE :employNo";
        String employNameStr = "FROM Emp e WHERE e.employName LIKE :employName";
        String employNoAndEmployName="FROM Emp e WHERE e.employNo LIKE :employNo OR e.employName LIKE :employName ";
        String defaultDeptStr="FROM Emp e";
        String deptIdStr = "FROM Emp e WHERE e.dept.id=:deptId";
        List<Emp> emps = null;

        Session session = sf.getCurrentSession();
        session.beginTransaction();
        if(employNo.trim().isEmpty()  && ( !(employName.trim().isEmpty()) )){
            emps=(List<Emp>)session.createQuery(employNameStr).setParameter("employName", "%"+employName+"%").list();
        }else if( (!employNo.trim().isEmpty()) && employName.trim().isEmpty() ){
            emps=(List<Emp>)session.createQuery(employNoStr).setParameter("employNo", "%"+employNo+"%").list();
        }else if(!(employNo.trim().isEmpty()) || (!(employName.trim().isEmpty())) ){
            emps=(List<Emp>)session.createQuery(employNoAndEmployName).setParameter("employNo", "%"+employNo+"%").setParameter("employName", "%"+employName+"%").list();
        }else if(deptId==0){
            emps=(List<Emp>)session.createQuery(defaultDeptStr).list();
        }else{
            emps=(List<Emp>)session.createQuery(deptIdStr).setParameter("deptId", deptId).list();
        }
        session.getTransaction().commit();
        return emps;
    }
}

你可能感兴趣的:(Hibernate,HQL,职场,like,休闲)