JAVA实现日期搜索框
场景:我们在项目中经常会遇到前台传两个时间日期进行检索的情况,所以我们需要掌握此方法,虽然简单,但操作而言仍然存在许多值得注意的地方。
两种方式实现日期搜索框
第一种,@GetMapping实现
controller直接传startTime/endTime
@GetMapping("/search")
public List<User> searchUser(@RequestParam(value = "startTime", required = false) String startTime,
@RequestParam(value = "endTime", required = false) String endTime){
return userService.search(startTime,endTime);
}
mapper.xml (注意date_format(xx,‘%Y-%m-%d’)不要写成yy-MM-dd,格式一定要写正确)
<select id="search" resultType="com.wlb.file.pojo.User">
select id, name, sex, age, birthday from user
where
1 = 1
-- 方案一
<if test="startTime != null and startTime != ''">
<![CDATA[ AND DATE_FORMAT(birthday,'%Y-%m-%d') >= #{startTime} ]]>
</if>
<if test="endTime != null and endTime != ''">
<![CDATA[ AND DATE_FORMAT(birthday,'%Y-%m-%d') <= #{endTime} ]]>
</if>
-- 方案二
<!-- <if test="startTime!=null and startTime != ''">-->
<!-- and DATE_FORMAT(birthday,'%Y-%d-%m') >= #{startTime}-->
<!-- </if>-->
<!-- <if test="endTime!=null and endTime != ''">-->
<!-- AND DATE_FORMAT(birthday,'%Y-%d-%m') <=#{endTime}-->
<!-- </if>-->
order by birthday desc
</select>
第二种 @PostMapping+dto封装
dto (注意属性值要小写,遵守命名规范)
@Data
public class UserDto {
private String dateFrom;
private String dateTo;
}
controller
@PostMapping("/search2")
public List<User> search2(@RequestBody UserDto userDto){
log.info("userDto.getDateFrom:{},userDto.getDateTo:{}",userDto.getDateFrom(),userDto.getDateTo());
return userService.search2(userDto);
}
mapper.xml (注意parameterType要对应上dto所在的路径)
<select id="search2" resultType="com.wlb.file.pojo.User" parameterType="com.wlb.file.dto.UserDto">
select id, name, sex, age, birthday from user
where
1 = 1
<if test="userDto.dateFrom != null and userDto.dateFrom != ''">
<![CDATA[ AND DATE_FORMAT(birthday,'%Y-%m-%d') >= #{userDto.dateFrom} ]]>
</if>
<if test="userDto.dateTo != null and userDto.dateTo != ''">
<![CDATA[ AND DATE_FORMAT(birthday,'%Y-%m-%d') <= #{userDto.dateTo } ]]>
</if>
order by birthday desc
</select>
Test 测试日期格式传参的可行性
测试第一种方案—可行
测试第二种方案—可行
创作不易,如果这篇文章对你有所帮助,麻烦给个小小的赞叭~!