如何使用JPA Criteria Query重写此查询?

时间:2011-04-08 11:21:40

标签: jpa criteriaquery

public class Entity {
private boolean suspended;

private String code;

@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
@DateTimeFormat(style = "S-")
private DateTime validFrom;

@Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime")
@DateTimeFormat(style = "S-")
private DateTime validTill;
}

查询的含义:“代码在给定的时间有效期内是唯一的吗?”

如何重写此查询:

select count(o) from Entity o 
where o <> :this and o.code = :code and (
  (o.validFrom between :validFrom and :validTill and not o.suspended) or
  (o.validTill between :validFrom and :validTill and not o.suspended) or 
  (:validFrom between o.validFrom and o.validTill and not o.suspended)
)

1 个答案:

答案 0 :(得分:4)

CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Entity> cQuery = builder.createQuery(Entity.class);
Root<Entity> root = cQuery.from(Entity.class);

Predicate pValid1 = builder.between(root.get("ValidFrom"), validFrom, validTill);
Predicate pValid2 = builder.between(root.get("ValidTill"), validFrom, validTill);
Predicate pValid3 = builder.and(builder.lessThan(root.get("validTill"), balidFrom),builder.greaterThan(root.get("ValidFrom",validfrom)));

Predicate pSuspend = builder.not(root.get("Suspended"),true);

ExecutableQuery qFinal = em.createQuery(cQuery.select(root).where(builder.and(pSuspend,builder.or(pValid1,pvalid2,pvalid3))))

它应该以这种方式工作。应该可以调整元数据对象,尽管我还没有这样做。