91 lines
3.6 KiB
Java

package com.xkrs.util;
import com.xkrs.dao.EquipmentDao;
import com.xkrs.dao.FireDao;
import com.xkrs.dao.WeatherDao;
import com.xkrs.model.entity.Equipment;
import com.xkrs.model.entity.Fire;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: XinYi Song
* @Date: 2022/2/14 11:29
*/
@Component
public class Query {
@Resource
private FireDao fireDao;
@Resource
private EquipmentDao equipmentDao;
/**
* 根据设备编号和时间段动态查询报警信息
* @param startTime
* @param endTime
* @return
*/
public List<Fire> selectFireBetweenTime(String code, String startTime, String endTime) {
Specification<Fire> specification = new Specification<Fire>() {
@Override
public Predicate toPredicate(Root<Fire> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
List<Predicate> list = new ArrayList<>();
if (code != null && !"".equals(code)) {
list.add(criteriaBuilder.equal(root.get("deviceCode").as(String.class), code));
}
if(startTime != null && !"".equals(startTime)){
list.add(criteriaBuilder.greaterThanOrEqualTo(root.get("alarmDate").as(String.class), startTime));
}
if(endTime != null && !"".equals(endTime)){
list.add(criteriaBuilder.lessThanOrEqualTo(root.get("alarmDate").as(String.class), endTime));
}
Predicate[] predicates = new Predicate[list.size()];
return criteriaBuilder.and(list.toArray(predicates));
}
};
return fireDao.findAll(specification);
}
/**
* 根据不同行业查询设备信息
* @param agriculture
* @param habitat
* @param waterConservancy
* @param forestry
* @return
*/
public List<Equipment> selectEquipment(String agriculture, String habitat, String waterConservancy, String forestry) {
Specification<Equipment> specification = new Specification<Equipment>() {
@Override
public Predicate toPredicate(Root<Equipment> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
List<Predicate> list = new ArrayList<>();
if (agriculture != null && !"".equals(agriculture)) {
list.add(criteriaBuilder.equal(root.get("agriculture").as(String.class), agriculture));
}
if (habitat != null && !"".equals(habitat)) {
list.add(criteriaBuilder.equal(root.get("habitat").as(String.class), habitat));
}
if (waterConservancy != null && !"".equals(waterConservancy)) {
list.add(criteriaBuilder.equal(root.get("waterConservancy").as(String.class), waterConservancy));
}
if (forestry != null && !"".equals(forestry)) {
list.add(criteriaBuilder.equal(root.get("forestry").as(String.class), forestry));
}
Predicate[] predicates = new Predicate[list.size()];
return criteriaBuilder.and(list.toArray(predicates));
}
};
return equipmentDao.findAll(specification);
}
}