使用JPA 2.1 Criteria API之间的LocalDate [英] LocalDate between using JPA 2.1 Criteria API
本文介绍了使用JPA 2.1 Criteria API之间的LocalDate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的实体中,我有两个字段:
In my entity I have two fields :
private LocalDate startDate = LocalDate.of(1900, 1, 1);
private LocalDate endDate = LocalDate.of(3000, 1, 1);
使用JPA Criteria API我想选择 LocalDate.now()的实体> startDate
和 LocalDate.now()< endDate
。
Using JPA Criteria API I want to select entities where LocalDate.now() > startDate
and LocalDate.now() < endDate
.
我试过以下内容:
predicates.add(builder.greaterThan(LocalDate.now(), path.<LocalDate> get(Entity_.startDate)));
predicates.add(builder.lessThan(builder.currentDate(), path.<LocalDate> get(Entity_.endDate)));
但我收到此错误:
The method greaterThan(Expression<? extends Y>, Expression<? extends Y>) in the type CriteriaBuilder is not applicable for the arguments (LocalDate, Path<LocalDate>)
我也试过这个:
predicates.add(builder.between(builder.currentDate(), path.<LocalDate> get(Entity_.startDate), path.<LocalDate> get(Entity_.endDate)));
我收到以下错误:
The method between(Expression<? extends Y>, Expression<? extends Y>, Expression<? extends Y>) in the type CriteriaBuilder is not applicable for the arguments (Expression<Date>, Path<LocalDate>, Path<LocalDate>)
我该如何解决这个问题?
How can I solve this ?
推荐答案
由于 JPA 2.1,您似乎需要
尚未直接支持 AttributeConverter
LocalDate
。假设你有实体
喜欢
@Entity
@Getter
public class LocalDateEntity {
@Id
@GeneratedValue
private Long id;
@Setter
private LocalDate startDate = LocalDate.of(1900, 1, 1);
@Setter
private LocalDate endDate = LocalDate.of(3000, 1, 1);
}
你可以使用 AttributeConverter
喜欢
// import java.sql.Date not java.util.Date;
@Converter(autoApply = true) // this makes it to apply anywhere there is a need
public class LocalDateConverter implements AttributeConverter<LocalDate, Date> {
@Override
public Date convertToDatabaseColumn(LocalDate date) {
return Date.valueOf(date);
}
@Override
public LocalDate convertToEntityAttribute(Date value) {
return value.toLocalDate();
}
}
之后可以赚 CriteriaQuery
喜欢
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<LocalDateEntity> cq = cb.createQuery(LocalDateEntity.class);
Root<LocalDateEntity> from = cq.from(LocalDateEntity.class);
Expression<Date> expCurrDate = cb.currentDate();
cq.where(
cb.and(
cb.greaterThan(from.get("endDate"), expCurrDate)
,cb.lessThan(from.get("startDate"), expCurrDate)
// OR for example
// cb.lessThan(expCurrDate, from.get("endDate"))
// ,cb.greaterThan(expCurrDate, from.get("startDate"))
// both are expressions no matter in what order
// but note the change in Predicate lt vs. gt
)
);
TypedQuery<LocalDateEntity> tq = em.createQuery(cq);
注意:而Predicate 之间(.. )
也可以,但有点不同。它包括起点&结束日期。
NOTE: while Predicate between(..)
will also work but a bit different. It includes the starting & ending dates.
这篇关于使用JPA 2.1 Criteria API之间的LocalDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文