我不明白在这段代码中进行联接并在规范中添加谓词后如何返回查询。有人能帮我吗?
public class QueriesEntity {
@Column(name = "query_id")
@Id
private int queryId;
private String name;
private String description;
private String query;
private Integer owner;
@Column(name = "conn_id")
private Integer dataSourceId;
@Column(name = "created_dt")
@Temporal(TemporalType.TIMESTAMP)
private Date createdDt;
@Column(name = "updated_dt")
@Temporal(TemporalType.TIMESTAMP)
private Date updatedDt;
@Column(name = "container_id")
private Integer containerId;
@OneToOne
@JoinColumn(name = "conn_id", updatable = false, insertable = false)
private DataSourceEntity dataSourceEntity;
公共静态规范筛选器(Integer containerId、Integer queryID、Integer datasourceId({
return new Specification<QueriesEntity>() {
private static final long serialVersionUID = 1L;
@Override
public Predicate toPredicate(Root<QueriesEntity> root, CriteriaQuery<?> query,
CriteriaBuilder criteriaBuilder) {
query = criteriaBuilder.createQuery(QueriesEntity.class);
root = query.from(QueriesEntity.class);
Join<QueriesEntity, DataSourceEntity> join = root.join("dataSourceEntity", JoinType.INNER);
List<Predicate> outerPreds = new ArrayList<>();
if (containerId != null) {
Predicate containerIdPred = criteriaBuilder.equal(root.get("containerId"), containerId);
outerPreds.add(containerIdPred);
}
if(queryID > 0) {
Predicate queryIdPred = criteriaBuilder.equal(root.get("queryId"), queryID);
outerPreds.add(queryIdPred);
}
if(datasourceId != null) {
Predicate datasourceIdPred = criteriaBuilder.equal(root.get("dataSourceId"), datasourceId);
outerPreds.add(datasourceIdPred);
}
return criteriaBuilder.and(outerPreds.toArray(new Predicate[outerPreds.size()]));
}
};
}
使用Join选项时,不应该使用root来获取字段,而是使用Join:
if (containerId != null) {
Predicate containerIdPred = criteriaBuilder.equal(join.get("containerId"), containerId);
outerPreds.add(containerIdPred);
}
示例代码:
public static Specification<QueriesEntity> filters(Integer containerId, Integer queryID, Integer datasourceId) {
return (root, query, cb) -> {
Join<QueriesEntity, DataSourceEntity> join = root.join("dataSourceEntity", JoinType.INNER);
List<Predicate> outerPreds = new ArrayList<>();
if (containerId != null) {
Predicate containerIdPred = cb.equal(join.get("containerId"), containerId);
outerPreds.add(containerIdPred);
}
if(queryID > 0) {
Predicate queryIdPred = cb.equal(join.get("queryId"), queryID);
outerPreds.add(queryIdPred);
}
if(datasourceId != null) {
Predicate datasourceIdPred = cb.equal(root.get("dataSourceId"), datasourceId);
outerPreds.add(datasourceIdPred);
}
return cb.and(outerPreds.stream().toArray(Predicate[]::new));
};
}