Spring Data JPA - How can I fetch data from a Date column using only month and day?(Spring Data JPA - 如何仅使用月份和日期从日期列中获取数据?)
问题描述
我有一个使用 mysql 的简单 Spring Data JPA 项目,我需要获取与日期和月份匹配的所有寄存器.我需要过滤的列是日期时间类型.
I have a simple Spring Data JPA project working with mysql and I need to fetch all registers that match the day and month. The column I need to filter is type Datetime.
1935-12-08 00:00:00
如果我想在数据库级别执行此操作,它可以正常工作:
If I want to do this in a db level it works fine:
SELECT * FROM my_database.event where event_date LIKE '%-12-08%';
它将日期视为字符串.现在我需要在我的存储库中执行此操作,但似乎没有任何效果.我尝试了基本的:
It treats the date as a string. Now I need to do this in my repository yet nothing seems to work. I tried the basic one:
List<Event> findByEventDateLike(
@Param("eventDate") Date eventDate);
但它说它返回一个非法参数异常,因为它是一个 Date 对象.我尝试了其他组合,但显然 spring data jpa 无法将日期与部分信息进行比较.
but it says it returns an illegal argument exception since it is a Date object. I tried other combinations but apparently spring data jpa can't compare dates with partial information.
注意:为了保持简洁,我尽量避免使用@Query 语句,但如果这是唯一的方法,那么它是一个有效的答案.
NOTE: To keep it clean I'm trying to avoid @Query sentences but if it is the only way to go, it is a valid answer.
我该怎么做?
推荐答案
使用 nativeQuery 模拟数据库中的查询.
Use nativeQuery to emulate the query in the Database.
@Query(value = "SELECT * FROM events WHERE event_date Like %?1%", nativeQuery = true)
List<Match> findByMatchMonthAndMatchDay(@Param ("eventDate") String eventDate);
数据库负责 LIKE 子句的日期/字符串之间的转换.
The DB takes care of the conversion between Date/String for the LIKE clause.
将参数作为-month-day"传递(例如:-12-08)将返回日期字段中包含该字符串的事件集合.
Passing the param as "-month-day" (e.g.: -12-08) will return a collection of events with that string in the date field.
这篇关于Spring Data JPA - 如何仅使用月份和日期从日期列中获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Spring Data JPA - 如何仅使用月份和日期从日期列中获取数据?
基础教程推荐
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 降序排序:Java Map 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01