JPA动态查询
CriteriaBuilder cb=entityManager.getCriteriaBuilder();
CriteriaQuery<T> query=cb.createQuery(clazz);
//clazz是你想要转换的类型,就是你的Entity.claa,如果你查的是count,就是Long.claa
Root<T> root=query.from(clazz);
query.select(root);//选取实体
Predicate predicate=cb.conjunction();//交集
predicate=cb.and(predicate,cb.equal(root.get("sex"),condition.get("sex")));
Predicate predicate=cb.disjunction();//并集
predicate=cb.or(predicate,cb.equal(root.get("sex"),condition.get("sex")));
JPA里面对类型控制比较严格,如下所示:
//比较大小
cb.gt(root.<Integer>get("degree"),(Integer) condition.get("degree"));
//like
cb.like(root.get("user").<String> get("nickName"),keyword)
//in 条件
root.get("tags").in(condition.get("tag"))
Java CriteriaBuilder.disjunction方法代碼示例
import javax.persistence.criteria.CriteriaBuilder; //導入方法依賴的package包/類
private Predicate getPredicateGlobalSearch(final Root<T> root,final CriteriaQuery<?>
query, final CriteriaBuilder cb, Predicate predicate) {
// check whether a global filter value exists
final String globalFilterValue = input.getSearch().getValue();
if (globalFilterValue != null && globalFilterValue.trim().length() > 0) {
LOGGER.fine("filtre global: {"+ globalFilterValue+"}");
Predicate matchOneColumnPredicate = cb.disjunction();
// add a 'WHERE .. LIKE' clause on each searchable column
for (final DatatableColumn column : input.getColumns()) {
if (column.getSearchable()) {
LOGGER.log(Level.FINE, "filtre global pour colonne: {}", column);
final Expression<String> expression =
DatatableHelper.getExpression(
root, column.getData(), String.class);
matchOneColumnPredicate =cb.or(matchOneColumnPredicate,
cb.like(cb.lower(expression),
getLikeFilterValue(globalFilterValue),
ESCAPE_CHAR));
}
}
predicate = cb.and(predicate, matchOneColumnPredicate);
}
return predicate;
}