How to rewrite this query using JPA Criteria Query?

戏子无情 提交于 2019-12-08 00:57:40

问题


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;
}

Meaning of query: "Is the code unique in given time validity?"

How to rewrite this query:

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:


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))))

It should work this way. It should be possible to adapt the metadata object, although I didn't do that yet.



来源:https://stackoverflow.com/questions/5594309/how-to-rewrite-this-query-using-jpa-criteria-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!