对于日期类型的查询条件,除了使用java.util.Date
,还可以考虑使用java.time.LocalDate
或java.sql.Date
。
- 使用
java.time.LocalDate
:
public List<Equipment> getEquipmentByTypeNoAndDate(@Param("typeNo") String typeNo, @Param("date") LocalDate date);
在Mapper XML文件中,查询语句中的日期条件需要进行转换:
WHERE typeNo = #{typeNo} AND date = #{date, jdbcType=DATE}
在测试方法中,传入LocalDate
类型的日期参数。
- 使用
java.sql.Date
:
public List<Equipment> getEquipmentByTypeNoAndDate(@Param("typeNo") String typeNo, @Param("date") java.sql.Date date);
在Mapper XML文件中,查询语句中的日期条件需要进行转换:
WHERE typeNo = #{typeNo} AND date = #{date, jdbcType=DATE}
在测试方法中,传入java.sql.Date
类型的日期参数。
以下是使用java.time.LocalDate
和java.sql.Date
的示例代码:
使用java.time.LocalDate
:
@Test
public void testEquipment01() throws IOException {
// 加载 MyBatis 配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-hello.xml");
// 创建 SqlSessionFactoryBuilder
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
// 根据配置文件创建 SqlSessionFactory
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
// 打开 SqlSession
try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) {
// 获取 EquipmentDao 接口的实例
EquipmentDao equipmentDao = sqlSession.getMapper(EquipmentDao.class);
// 构造 LocalDate 对象
LocalDate date = LocalDate.of(2022, 1, 1);
// 调用查询方法
List<Equipment> equipmentList = equipmentDao.getEquipmentByTypeNoAndDate("yourTypeNo", date);
// 处理查询结果
for (Equipment equipment : equipmentList) {
System.out.println(equipment);
}
}
}
使用java.sql.Date
:
@Test
public void testEquipment01() throws IOException {
// 加载 MyBatis 配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-hello.xml");
// 创建 SqlSessionFactoryBuilder
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
// 根据配置文件创建 SqlSessionFactory
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
// 打开 SqlSession
try (SqlSession sqlSession = sqlSessionFactory.openSession(true)) {
// 获取 EquipmentDao 接口的实例
EquipmentDao equipmentDao = sqlSession.getMapper(EquipmentDao.class);
// 构造 java.sql.Date 对象
java.sql.Date date = java.sql.Date.valueOf("2022-01-01");
// 调用查询方法
List<Equipment> equipmentList = equipmentDao.getEquipmentByTypeNoAndDate("yourTypeNo", date);
// 处理查询结果
for (Equipment equipment : equipmentList) {
System.out.println(equipment);
}
}
}