gpt4 book ai didi

java - 使用 JPA 2.1 Criteria API 之间的 LocalDate

转载 作者:行者123 更新时间:2023-11-30 06:22:01 25 4
gpt4 key购买 nike

在我的实体中,我有两个字段:

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 .

我尝试如下:

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

我该如何解决这个问题?

最佳答案

看来您需要一个AttributeConverter,因为JPA 2.1尚不直接支持LocalDate。假设您有一个Entity,例如

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

注意:而谓词 Between(..) 也可以工作,但有点不同。它包括开始和结束日期。

关于java - 使用 JPA 2.1 Criteria API 之间的 LocalDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47928424/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com