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) {
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);
}
}