mybatis 接口通过hashmap传值进行查询(6)

mybatis 接口通过hashmap传值进行查询

一、应用文件包含:pom文件与(5)相同、实体类Person 与(5)相同、操作数据库接口类PersonMapper、mapper文件及其测试文件

二、应用代码

1、PersonMapper代码

package com.mybatis03.mapper;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * @author :jack.zhao
 * @Describe: 操作mybatis接口
 * @date :2021-10-16 22:55
 */
public interface PersonMapper {
    List<Person> queryPersonByAgeAndNameWithHashMap(Map map);
}

2、mapper文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mybatis03.mapper.PersonMapper">
    <!-- hashMap传值查询 -->
    <select id="queryPersonByAgeAndNameWithHashMap" parameterType="HashMap" resultType="com.mybatis03.bean.Person">
        select
        id,name,age,sex
        from
        t_person_01
        where id like #{id} or name like '%${name}%'
    </select>
</mapper>

3、测试类

主要代码如下:
。。。。。。。。。。。。
    @Test
    public void queryPersonByAgeAndNameWithHashMap() throws Exception{
        Reader reader = Resources.getResourceAsReader("mybatis-03.xml");
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
        SqlSession session = sessionFactory.openSession();
        Map<String,Object> personMap = new HashMap<String,Object>();
        personMap.put("id",1001);
        personMap.put("name","maliu");
        // 动态代理
        PersonMapper personMapper = session.getMapper(PersonMapper.class);
        List<Person> personList = personMapper.queryPersonByAgeAndNameWithHashMap(personMap);
        System.out.println("查询所有人员信息为:"+personList);
        session.close();
    }
。。。。。。。

查询结果:

查询所有人员信息为:[Person{id=1001, name='zhangsan', age=27, sex=true}, Person{id=1003, name='maliu', age=16, sex=true}]
原文地址:https://www.cnblogs.com/northeastTycoon/p/15418772.html