Hibernate hql 2

import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.saipu.scaffold.shiro.entity.view.AlarmRecord;

public class AlarmRecordRepositoryImpl {

    @PersistenceContext
    private EntityManager em;

    public EntityManager getEm() {
        return em;
    }

    public void setEm(EntityManager em) {
        this.em = em;
    }

    public List<AlarmRecord> findAlarmRecords(Long areaId, String username, Date beginDate, Date endDate){

        String hql = null; // 查询语句
        hql = "select ar from AlarmRecord ar  where  ";
        hql += this.prepareHql(areaId, username, beginDate, endDate);

        Query q = em.createQuery(hql);

        this.setValue(areaId, username, beginDate, endDate, q);

        return q.getResultList();
    }

    /** 拼接查询条件 */
    private String prepareHql(Long areaId, String username, Date beginDate, Date endDate) {
        // TODO Auto-generated method stub
        StringBuffer buffer = new StringBuffer();

        buffer.append(" ar.sensor.area.id=:areaId ");
        buffer.append(" and ar.creatorName=:username ");
        if (beginDate != null)
            buffer.append(" and ar.occurTime>:beginTime");
        if (endDate != null)
            buffer.append(" and ar.occurTime<:endTime");

        return buffer.toString();
    }

    /** 设置 查询条件的值 */
    private void setValue(Long areaId, String username, Date beginDate, Date endDate, Query q) {

        q.setParameter("areaId", areaId);
        q.setParameter("username", username);
        if (beginDate != null)
            q.setParameter("beginTime", beginDate);
        if (endDate != null)
            q.setParameter("endTime", endDate);
    }
}
posted on 2017-07-19 16:22  dreamstar  阅读(48)  评论(0编辑  收藏  举报