mybatis中查询一段时区的数据
Blog.java
@NoArgsConstructor
@AllArgsConstructor
@Data
public class Blog {
private Integer id;//id
private String title;//标题
private String author;//作者
private Date createTime;//创建时间
private Integer views;//浏览量
}
Blog接口
public interface BlogMapper {
/**
* 查询时间
* @param map
* @return
*/
List<Blog> queryByTime(Map<String,Object> map);
}
Mapper.xml
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.nb.mapper.BlogMapper">
<!--
第一种:使用#{}形式
select id,title,create_time,views,author
from blog where create_time between #{startTime} and #{endTime}
第二种:使用${}需要拼接
select id,title,create_time,views,author
from blog where create_time between '${startTime}' and '${endTime}'
-->
<select id="queryByTime" parameterType="map" resultType="com.nb.pojo.Blog">
select id,title,create_time,views,author
from blog where create_time between #{startTime} and #{endTime}
</select>
</mapper>
测试代码:
//时间测试
@Test
public void timeTest(){
Map<String,Object> map = new HashMap<>();
Date startTime = new Date(122,0,18);
Date endTime = new Date(122,0,20);
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
map.put("startTime","2022-01-18");
map.put("endTime","2022-01-20");
List<Blog> blogs = mapper.queryByTime(map);
for (Blog blog : blogs) {
System.out.println("blog = " + blog);
}
}
测试结果:
- 字符格式
第一种方式:
第二种方式:
- 日期格式
//时间测试
@Test
public void timeTest(){
Map<String,Object> map = new HashMap<>();
Date startTime = new Date(122,0,18);
Date endTime = new Date(122,0,20);
//日期格式
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//map.put("startTime","2020-01-18");字符串格式也可以
map.put("startTime",format.format(startTime));//或者使用日期格式类进行转化
map.put("endTime",format.format(endTime));
List<Blog> blogs = mapper.queryByTime(map);
for (Blog blog : blogs) {
System.out.println("blog = " + blog);
}
}