java对数据库中Date类型的处理(其中的一种方案)

对于日期类型的查询条件,除了使用java.util.Date,还可以考虑使用java.time.LocalDatejava.sql.Date

  1. 使用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类型的日期参数。

  1. 使用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.LocalDatejava.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);
        }
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值