使用JPA 2.1 Criteria API之间的LocalDate

时间:2017-12-21 15:51:41

标签: java jpa jpa-2.1 jpa-criteria

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

private LocalDate startDate = LocalDate.of(1900, 1, 1);
private LocalDate endDate = LocalDate.of(3000, 1, 1);

使用JPA Criteria API我想选择LocalDate.now() > startDateLocalDate.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>)

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

由于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(..)也会有效,但有点不同。它包括起始&amp;结束日期。