在 MyBatis 中比较 Java 日期类型和 MySQL datetime 类型时,需要注意类型转换和格式匹配问题。以下是几种常见的解决方案:
MyBatis 会自动处理 Java 的 java.util.Date
、java.sql.Date
、java.sql.Timestamp
与 MySQL 的 datetime 类型之间的转换:
<select id="selectByDate" resultType="YourEntity">
SELECT * FROM your_table
WHERE create_time = #{dateParam, jdbcType=TIMESTAMP}
</select>
在 SQL 中使用 MySQL 的日期函数进行精确比较:
<select id="selectByDate" resultType="YourEntity">
SELECT * FROM your_table
WHERE DATE(create_time) = DATE(#{dateParam})
</select>
如果需要特定格式的比较,可以:
<select id="selectByDate" resultType="YourEntity">
SELECT * FROM your_table
WHERE DATE_FORMAT(create_time, '%Y-%m-%d') = DATE_FORMAT(#{dateParam}, '%Y-%m-%d')
</select>
对于日期范围查询:
<select id="selectByDateRange" resultType="YourEntity">
SELECT * FROM your_table
WHERE create_time BETWEEN #{startDate} AND #{endDate}
</select>
如果遇到时区问题,可以在连接字符串中指定时区:
jdbc:mysql://localhost:3306/your_db?serverTimezone=UTC
或者在 SQL 中使用 CONVERT_TZ 函数:
<select id="selectByDate" resultType="YourEntity">
SELECT * FROM your_table
WHERE CONVERT_TZ(create_time, 'SYSTEM', 'UTC') = #{dateParam}
</select>
java.time
包中的类(如 LocalDateTime
)作为日期类型(MyBatis 3.5+ 支持)// 使用 java.time 的示例
public List<YourEntity> selectByLocalDate(@Param("dateParam") LocalDateTime dateParam);
<select id="selectByLocalDate" resultType="YourEntity">
SELECT * FROM your_table
WHERE create_time = #{dateParam}
</select>