When performing date queries in MyBatis, if you need to add time after the date (for example 23:59:59
) to ensure that the query includes the entire time range of the date, you can do it in the following ways:
1. Direct operation in SQL
Add time directly to date in SQL query, for example:
SELECT * FROM your_table
WHERE your_datetime_column <= CONCAT(#{yourDate}, ' 23:59:59');
Here, #{yourDate}
it is the parameter passed in by MyBatis, and CONCAT
the function concatenates the date and time strings together.
2. Processing in Java code
You can set the time in Java code before passing the date to MyBatis:
// 假设yourDate是一个LocalDate对象
LocalDateTime endOfDay = yourDate.atTime(23, 59, 59);
// 然后你可以将endOfDay作为参数传递给MyBatis
In the MyBatis mapper file, you can use this endOfDay
object directly:
<select id="selectByDay" resultType="YourType">
SELECT * FROM your_table
WHERE your_datetime_column <= #{endOfDay}
</select>
3. Use database functions
Some databases provide functions to handle dates and times. For example, MySQL has a DATE_ADD
function that can be used to add time intervals:
SELECT * FROM your_table
WHERE your_datetime_column <= DATE_ADD(#{yourDate}, INTERVAL '23:59:59' HOUR_SECOND);
4. Use MyBatis <bind>
tags
In MyBatis' mapper XML, you can use <bind>
tags to create a local variable that combines a date and time:
<select id="selectByDay" resultType="YourType">
<bind name="endOfDay" value="'${yourDate} 23:59:59'" />
SELECT * FROM your_table
WHERE your_datetime_column <= #{endOfDay}
</select>
Note that you use ${}
instead #{}
to avoid MyBatis preprocessing the date, which means you need to make sure yourDate
the format is correct and prevent SQL injection.