java - 按方法名称的 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());
}
解决方案
DailyStatistic
您可以尝试按国家名称和日期过滤此 jpa 方法命名
repository.findAllByCountryNameAndDateBetweenOrderByDateDesc(country.name,from, to);
推荐阅读
- java - 创建像 Spring DataSourceBuilder 一样工作的自定义构建器?
- android - Chrome 更新后未加载 Android 9 WebView(也是 admob 广告)
- cordova - 免费后如何检测用户是否购买了该应用程序?
- kotlin - 值不会在简单的计算中相加
- firebase - 如何获取文档数据并将其设置在屏幕上
- r - 使用百分比时的美学分组论点
- java - Android Pjsip:音频电话会议
- php - 邮件程序错误:SMTP 连接()失败。https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting 在我的代码中
- android - 当我将 `sqflite` 添加到我的 pubspec.yaml 时,为什么我的颤振应用程序会崩溃?
- python - 如何通过 django 将文件列表上传到 URL?