JPA 标准查询不同

2022-09-01 12:36:32

我正在尝试编写一个不同的条件查询,使用:

CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<RuleVar> query = builder.createQuery(RuleVar.class);
Root<RuleVar> ruleVariableRoot = query.from(RuleVar.class);
query.select(ruleVariableRoot.get("foo").<String>get("foo")).distinct(true);

基于 Javadoc for CriteriaQuery.select() 中的示例

CriteriaQuery<String> q = cb.createQuery(String.class);
 Root<Order> order = q.from(Order.class);
 q.select(order.get("shippingAddress").<String>get("state"));

但是,这给了我一个错误:

The method select(Selection<? extends RuleVar>) in the type CriteriaQuery<RuleVar> is not applicable for the arguments (Path<String>)

有人可以指出我做错了什么吗?或者如何从路径中获取选择对象?


答案 1

知道了。问题是我的CriteraQuery需要是String类型。这有效:

CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<String> query = builder.createQuery(String.class);
Root<RuleVar> ruleVariableRoot = query.from(RuleVar.class);
query.select(ruleVariableRoot.get(RuleVar_.varType)).distinct(true);

答案 2

推荐