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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值