dcsuibian
2022-07-09 23:01:59 +08:00
引用知乎的:
db 访问分为这么几种
1. 写 sql ,各个 db 差异要自己适配
2. 写 dsl ,屏蔽了 db 差异,自动适配
3. 运行时或编译时自动合成 sql ,屏蔽 db 差异
我是第 3 种动态生成 sql 的,用的是 JPA 的 Specification ,代码大概是这个样子:
Specification<RecordPO> spec = (root, query, cb) -> {
Path<String> termPath = root.get("term");
Path<Long> beginTimePath = root.get("beginTime");
Path<Long> endTimePath = root.get("endTime");
Predicate predicate = cb.equal(cb.literal(1), 1);
if (null != qo.getTerm()) {
predicate = cb.and(predicate, cb.equal(termPath, qo.getTerm()));
}
if (null != qo.getBeginTimeGreaterThanEqual()) {
predicate = cb.and(predicate, cb.greaterThanOrEqualTo(beginTimePath, qo.getBeginTimeGreaterThanEqual()));
}
if (null != qo.getEndTimeLessThanEqual()) {
predicate = cb.and(predicate, cb.lessThanOrEqualTo(endTimePath, qo.getEndTimeLessThanEqual()));
}
query.orderBy(cb.asc(root.get("endTime")));
return predicate;
};
return spec;