首页 > 解决方案 > 按方法名称的 Spring Data Jpa 查询在 LocalDate 的 BETWEEN 中无法正常工作

问题描述

我有两个表:“DailyStatistic”,ManyToOne 到“Country”。

public class DailyStatistic {
    @Id
    @GeneratedValue
    private Long id;
    @Column(columnDefinition = "DATE")
    private LocalDate date;
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "country_id")
    private Country country;

///

public class Country {

            @Id
            @GeneratedValue
            private Long id;
            private String name;

当我打电话时:

public interface DailyStatRepository extends JpaRepository<DailyStatistic, Long> {
...
List<DailyStatistic> findAllByCountryAndDateBetween(Country country, LocalDate from, LocalDate to);
...
}

我得到奇怪的结果:

2020-03-29
2020-03-28
2020-03-27
2020-03-30
2020-03-29

Hibernate 设置对象错误的日期,我得到两个具有相同日期的不同对象。

请帮忙解决问题。

我调用此方法的代码:

public class DataProvider {

    private final ForeignDataSource foreignDataSource;
    private final DailyStatRepository repository;
    private final CountryRepository countryRepository;

    @Autowired
    public DataProvider(ForeignDataSource foreignDataSource, 
                        DailyStatRepository repository, 
                        CountryRepository countryRepository) {
        this.foreignDataSource = foreignDataSource;
        this.repository = repository;
        this.countryRepository = countryRepository;
    }

public List<DailyStatistic> getCountryStatFromToDate(Long countryId,
                                                         LocalDate from,
                                                         LocalDate to) throws NoDataException {
        Country country = countryRepository.findById(countryId).orElseThrow(NoDataException::new);
        List<DailyStatistic> dailyStatisticList = repository.findAllByCountryAndDateBetween(country, from, to);
        for (DailyStatistic ds : dailyStatisticList) {
            System.out.println(ds.getDate());
        }

标签: javahibernatespring-bootspring-data-jpa

解决方案


DailyStatistic您可以尝试按国家名称和日期过滤此 jpa 方法命名

repository.findAllByCountryNameAndDateBetweenOrderByDateDesc(country.name,from, to);

推荐阅读