在Spring中使用Date创建JPA查询

时间:2018-01-22 13:16:48

标签: java spring postgresql spring-data-jpa jpql

这就是我的实体的样子:

@Entity
public class Registration {
@Id
@GeneratedValue
private Integer id;

@org.springframework.format.annotation.DateTimeFormat(pattern = "yyyy-MM-dd")
private LocalDate date;
}

这就是我的回购的样子:

@Query(value = "SELECT * FROM registration WHERE MONTH(date) = ?1 AND YEAR(date) = ?2")
List<Registration> findAll(Integer month, Integer year);

这将是服务:

public List<Registration> getCurrentRegistration() {
    LocalDate today = LocalDate.now();
    return registrationRepository.findAll(today.getMonth().getValue(), today.getYear());
}
public List<Registration> getRegistrations(Integer month, Integer year) {
    return registrationRepository.findAll(month, year);
}

如何将原始查询更改为JPA查询? JPA查询能否在postgresql和hsqldb上运行? 为什么JPA查询最适合春季应用程序? (或者他们为什么不这样做)

2 个答案:

答案 0 :(得分:3)

制作规范类并在其中编写以下规范方法。

import javax.persistence.criteria.Predicate;
import org.springframework.data.jpa.domain.Specification;

public class RegistrationSpecification {
public static Specification<Registration > registrationSpecForDate(
      LocalDate invoiceDate ) {
    return (root, cq, cb) -> {

      List<Predicate> predicates = new ArrayList<Predicate>();

      if (invoiceDate!=(null)) {
          predicates.add(cb.greaterThanOrEqualTo(root.get("date"), 
           invoiceDate));
        }

      return cb.and(predicates.toArray(new Predicate[0]));
    };
  }

然后在您的存储库中,在JPA的findAll()方法中注入此规范。

`public List<Registration> getRegistrations(LocalDate date) {
  return 
       registrationRepository.findAll
           (RegistrationSpecification.registrationSpecForDate(date));

`

答案 1 :(得分:2)

您可以使用QueryDSL JPA(https://github.com/querydsl/querydsl/tree/master/querydsl-jpa)来定义谓词:

Predicate createPredicate(Integer month, Integer year) {
    return QRegistration.date.year().eq(year).and(QRegistration.date.month().eq(month));
}

然后让你的repo扩展QueryDslPredicateExecutor:

public interface RegistrationRepository extends JpaRepository<Registration>, QueryDslPredicateExecutor {
  // Your query methods here
}

这包含一个List<T> findAll(Predicate predicate)方法,您可以将谓词传递给您以获取您所追踪的项目,例如:

registrationRepository.findAll(createPredicate(1, 1970));

有关在Spring中使用QueryDSL的更多信息,请参阅此处:https://spring.io/blog/2011/04/26/advanced-spring-data-jpa-specifications-and-querydsl/