记住官方文档永远是首选
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.springframework.data.jpa.domain.Specification;
import com.xxx.controller.logManage.LogSearchParamDTO;
import com.xxx.controller.trade.TradeParams;
/**
* 改进方向 1:能不能 通过反射 ,只要---
* 相关知识请自行查阅JPA Criteria查询
// 过滤条件
// 1:过滤条件会被应用到SQL语句的FROM子句中。在criteria
// 查询中,查询条件通过Predicate或Expression实例应用到CriteriaQuery对象上。
// 2:这些条件使用 CriteriaQuery .where 方法应用到CriteriaQuery 对象上
// 3:CriteriaBuilder也作为Predicate实例的工厂,通过调用CriteriaBuilder 的条件方法(
// equal,notEqual, gt, ge,lt, le,between,like等)创建Predicate对象。
// 4:复合的Predicate 语句可以使用CriteriaBuilder的and, or andnot 方法构建。
* @author 小言
* @date 2017年11月27日
* @time 上午10:44:53
* @version ╮(╯▽╰)╭
*/
public class SpecificationBuilderForOperateLog {
public static Specification buildSpecification(Class clazz,
final LogSearchParamDTO logSearchParamDTO) {
return new Specification() {
@Override
public Predicate toPredicate(Root root, CriteriaQuery> query, CriteriaBuilder cb) {
List predicate = new ArrayList();
Timestamp startTime = logSearchParamDTO.getStartTime();
Timestamp endTime = logSearchParamDTO.getEndTime();
// 时间段
if (startTime != null && endTime != null) {
predicate.add(cb.between(root. get("logTime"), startTime, endTime));
}
// 操作日志查询栏
String searchCondition = logSearchParamDTO.getSearchCondition();
if (searchCondition != null && !searchCondition.equals("")) {
predicate.add(cb.or(cb.equal(root. get("operatorName"), searchCondition),
cb.equal(root. get("operatorId"), searchCondition)));
}
// 操作日志用户类型
String operatorType = logSearchParamDTO.getOperatorType();
System.out.println("operatorType=="+operatorType);
if (operatorType != null ){
predicate.add(cb.equal(root. get("operatorType"), operatorType));
}
Predicate[] pre = new Predicate[predicate.size()];
// System.out.println("pre=="+predicate.toArray(pre));
query.where(predicate.toArray(pre));
return query.getRestriction();
}
};
}
}
下面是实际开发例子
controller层
@Controller
@RequestMapping(value = "/operateLog")
public class BgOperateLogController {
@Autowired
private BgOperateLogService bgOperateLogService;
@ResponseBody
@PostMapping("/findOperateLogByCondition")
public Result findOperateLogByCondition(@RequestBody LogSearchParamDTO logSearchParamDTO) {
System.out.println("logSearchParamDTO="+logSearchParamDTO);
Map result = new HashMap<>();
String start = logSearchParamDTO.getStart();
String end = logSearchParamDTO.getEnd();
if (start != null && end == null) {
return new Result(1001, "操作日志查询错误,时间参数缺少结束时间", result);
}
if (end != null && start == null) {
return new Result(1001, "操作日志查询错误,时间参数缺少开始时间", result);
}
//时间
long startTimeTimestamp = 0L;
long endTimeTimestamp = System.currentTimeMillis();
if(start != null && end != null){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date startTime;
Date endTime;
try {
startTime = sdf.parse(start);
endTime = sdf.parse(end);
startTimeTimestamp = startTime.getTime();
endTimeTimestamp = endTime.getTime();
} catch (ParseException e) {
e.printStackTrace();
return new Result(1001, "操作日志查询错误,转换日期出错", result);
}
}
String condition = logSearchParamDTO.getSearchCondition();
Integer pageNumber = logSearchParamDTO.getPageNumber()-1;
Integer pageSize = logSearchParamDTO.getPageSize() ;
String operatorType =logSearchParamDTO.getOperatorType();
Page findByCondition = bgOperateLogService.findByCondition(new Timestamp(startTimeTimestamp),
new Timestamp(endTimeTimestamp),
condition,operatorType, pageNumber, pageSize);
// 这些字段必须有,暂时没有做校验
List list = findByCondition.getContent();
result.put("totalPages", findByCondition.getTotalPages());
result.put("pageNumber", pageNumber+1);
result.put("list", list);
return new Result(1002, "操作日志查询成功", result);
}
}
DTO
@Data
public class LogSearchParamDTO {
//前端传来的时间参数
private String start;
private String end;
private Timestamp startTime;
private Timestamp endTime;
private String searchCondition;
//操作日志查询参数
//操作用户类型(0,消费者,1商家,2后台人员)
private String operatorType;
private Integer pageNumber;
private Integer pageSize;
//登陆日志查询条件
public LogSearchParamDTO(Timestamp startTime, Timestamp endTime, String searchCondition) {
this.startTime = startTime;
this.endTime = endTime;
this.searchCondition = searchCondition;
}
public LogSearchParamDTO() {}
//操作日志查询条件
public LogSearchParamDTO(Timestamp startTime, Timestamp endTime, String searchCondition, String operatorType) {
this.startTime = startTime;
this.endTime = endTime;
this.searchCondition = searchCondition;
this.operatorType = operatorType;
}
}
service 层
@Override
public Page findByCondition(Timestamp start,
Timestamp end, String condition ,String operatorType,
int pageNumber, int pageSize) {
Sort sort = new Sort(Sort.Direction.DESC, "logTime");
Pageable pageable = new PageRequest(pageNumber, pageSize, sort);
LogSearchParamDTO operateLog = new LogSearchParamDTO(start, end, condition,operatorType);
Page page = bgOperateLogDao
.findAll(SpecificationBuilderForOperateLog.buildSpecification(BgOperateLog.class,operateLog), pageable);
return page;
}
dao层
import java.io.Serializable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import com.xxx.entity.BgOperateLog;
@Repository
public interface BgOperateLogDao extends JpaRepository,JpaSpecificationExecutor{}
entity层
@Data
@Entity
public class BgOperateLog implements java.io.Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String logText;
private String operatorId;
private String operatorName;
private String operatorType;
private String ip;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Timestamp logTime;
}