Mybatis的map用法

当Mybatis传过来的值是map类型的时候,有两种处理方法

1、将数值装入类封装起来

public interface IStudentDao {

    // 根据姓名和年龄查询
    List<Student> selectStudentsByCondition(Map<String, Object> map);

    // 根据姓名和年龄查询
    List<Student> selectStudentsByCondition2(String name,int age);
}

2、map有动态加载,所以不用impl,只需dao 的抽象方法和id名称一样就可以

<?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.xml相同的id名所以namespace改为对应的到的包路径-->
<mapper namespace="com.liuya.demo.mybatis.dysnamic.dao.IStudentDao">
    <!-- 配置数据库和实体类的字段 -->
    <resultMap id="studentMapper" type="Student">
        <id column="T_ID" property="id"/>
        <result column="T_NAME" property="name"/>
        <result column="T_AGE" property="age"/>
        <result column="T_SCORE" property="score"/>
    </resultMap>

    <!-- 根据姓氏模糊查询 -->
    <select id="selectStudentsByCondition" resultMap="studentMapper">
        select T_NAME,T_AGE,T_SCORE
        from STUDENT
        where T_NAME like '%' #{nameCon} '%'
        AND T_AGE > #{ageCon}
        AND T_SCORE > #{student1.score }
    </select>

    <!-- 根据姓氏模糊查询,#{}大括号里是索引
          #{}中可以放什么内容?
          (1)参数对象的属性
          (2)随意内容,此时的#{}是占位符
          (3)参数为map时的key
          (4)参数为map时,若key所对应的value为对象,则可将对象的属性放入
          (5)参数的索引号
    -->
    <select id="selectStudentsByCondition2" resultMap="studentMapper">
        select T_NAME,T_AGE,T_SCORE
        from STUDENT
        where T_NAME like '%' #{0} '%'
        AND T_AGE > #{1}
    </select>


</mapper>

3、对其测试

public class MyTest {

    private IStudentDao idao;
    private SqlSession sqlSession;

    @Before
    public void before() {
        sqlSession = MybatisUtil.getSqlSession();
        idao = sqlSession.getMapper(IStudentDao.class);
    }

    @After
    public void after() {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }


    // 查询一个姓张的,年龄大于24,并且成绩比田七高的学生
    @Test
    public void testSelectStudentsByCondition() {
        System.out.println("开始查询学生");
        Student student1 = new Student("",21,66);

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("nameCon","张");
        map.put("ageCon",24);
        map.put("student1",student1);

        List<Student> students = idao.selectStudentsByCondition(map);
        for (Student student : students) {
            System.out.println(student);
        }
        System.out.println("查询学生成功");
    }

    // 查询一个姓张的,年龄大于24,并且成绩比田七高的学生
    @Test
    public void testSelectStudentsByCondition2() {
        System.out.println("开始查询学生");

        List<Student> students = idao.selectStudentsByCondition2("张",24);
        for (Student student : students) {
            System.out.println(student);
        }
        System.out.println("查询学生成功");
    }
}
原文地址:https://www.cnblogs.com/liuyangfirst/p/7470503.html