MyBatis学习总结(六):MyBatis动态sql之foreach标签和bind标签

1、foreach标签

<foreach> 标签主要用在构建 in 条件中,它可以在 SQL 语句中迭代一个集合。

<foreach> 标签的属性主要有 item、index、collection、open、separator、close。

  • item 表示集合中每一个元素进行迭代时的别名。
  • index 指定一个名字,用于表示在迭代过程中每次迭代到的位置。
  • open 表示该语句以什么开始。
  • separator 表示在每次进行迭代之间以什么符号作为分隔符。
  • close 表示以什么结束。

在使用 <foreach> 元素时,最关键、最容易出错的是 collection 属性,该属性是必选的,但在不同情况下该属性的值是不一样的,主要有以下 3 种情况:

  • 如果传入的是单参数且参数类型是一个 List,collection 属性值为 list。
  • 如果传入的是单参数且参数类型是一个 array 数组,collection 的属性值为 array。
  • 如果传入的参数是多个,需要把它们封装成一个 Map,当然单参数也可以封装成 Map。Map 的 key 是参数名,collection 属性值是传入的 List 或 array 对象在自己封装的 Map 中的 key。

接下来针对上述三种情况进行演示:

(1)单参数且参数类型是List

在IStudentDao添加方法。

    List<Student> forEachTest1(List<Integer> list);

在studentMapper.xml中添加sql映射语句。

    <select id="forEachTest1" resultType="com.day1.entity.Student">
        select * from t_student where age in
        <foreach collection="list" index="index" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>

进行测试。

    @Test
    public void testForEach01() throws IOException {
        //1、读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapperConfig.xml");
        //2、创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3、使用工厂生产SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //4、使用SqlSession创建dao接口的代理对象
        IStudentDao studentDao = sqlSession.getMapper(IStudentDao.class);
        //5、使用代理对象执行方案
        List<Integer> list = new ArrayList<>();
        list.add(21);
        list.add(43);
        list.add(19);
        List<Student> students = studentDao.forEachTest1(list);
        for(Student stu : students){
            System.out.println(stu);
        }
        //6、释放资源
        sqlSession.close();
        in.close();
    }

(2)单参数且参数类型是array

在IStudentDao添加方法。

    List<Student> forEachTest2(int[] ages);

在studentMapper.xml中添加sql映射语句。

<select id="forEachTest2" resultType="com.day1.entity.Student">
        select * from t_student where age in
        <foreach collection="array" index="index" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>

进行测试。

    @Test
    public void testForEach02() throws IOException {
        //1、读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapperConfig.xml");
        //2、创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3、使用工厂生产SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //4、使用SqlSession创建dao接口的代理对象
        IStudentDao studentDao = sqlSession.getMapper(IStudentDao.class);
        //5、使用代理对象执行方案
        int[] ages = new int[]{19, 56};
        List<Student> students = studentDao.forEachTest2(ages);
        for(Student stu : students){
            System.out.println(stu);
        }
        //6、释放资源
        sqlSession.close();
        in.close();
    }

(3)封装map

在IStudentDao添加方法。

    List<Student> forEachTest3(Map<String, Object> map);

在studentMapper.xml中添加sql映射语句。

<select id="forEachTest3" resultType="com.day1.entity.Student">
        select * from t_student where age > #{age} or address in
        <foreach collection="locations" index="index" item="item" open="(" separator="," close=")">
            #{item}
        </foreach>
    </select>

进行测试。

    @Test
    public void testForEach03() throws IOException {
        //1、读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapperConfig.xml");
        //2、创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3、使用工厂生产SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //4、使用SqlSession创建dao接口的代理对象
        IStudentDao studentDao = sqlSession.getMapper(IStudentDao.class);
        //5、使用代理对象执行方案
        List<String> locations = new ArrayList<>();
        locations.add("北京");
        locations.add("河北");
        locations.add("安徽");
        Map<String, Object> map = new HashMap<>();
        map.put("age", 30);
        map.put("locations", locations);
        List<Student> students = studentDao.forEachTest3(map);
        for(Student stu : students){
            System.out.println(stu);
        }
        //6、释放资源
        sqlSession.close();
        in.close();
    }

2、<bind>标签

通常在进行模糊查询时,如果使用“${}”拼接字符串,则无法防止 SQL 注入问题。如果使用字符串拼接函数或连接符号,但不同数据库的拼接函数或连接符号不同,MySQL 用的是的 concat 函数、Oracle 则是连接符号“||”,这样 SQL 映射文件就需要根据不同的数据库提供不同的实现,显然比较麻烦,且不利于代码的移植。MyBatis 提供了 <bind> 元素来解决这一问题。

<bind>标签可以使用OGNL表达式创建一个变量并将其绑定到上下文中。<bind>标签的两个属性都是必选项:name 为绑定到上下文的变量名;value 为 OGNL 表达式。

(1)在IStudentDao添加方法。

    List<Student> testBind(Student student);

(2)在studentMapper.xml中添加sql映射语句。

<!--使用bind元素进行模糊查询-->
    <select id="testBind" resultType="com.day1.entity.Student" parameterType= "com.day1.entity.Student">
        <!-- bind 中的 username 是 com.day1.entity.Student 的属性名-->
        <bind name="username" value="'%' + username + '%'"/>
        select * from t_student where username like #{username}
    </select>

(3)进行测试。

    @Test
    public void testBind() throws IOException {
        //1、读取配置文件
        InputStream in = Resources.getResourceAsStream("SqlMapperConfig.xml");
        //2、创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3、使用工厂生产SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //4、使用SqlSession创建dao接口的代理对象
        IStudentDao studentDao = sqlSession.getMapper(IStudentDao.class);
        //5、使用代理对象执行方案
        Student student = new Student();
        student.setUsername("王");
        List<Student> students = studentDao.testBind(student);
        for(Student stu : students){
            System.out.println(stu);
        }
        //6、释放资源
        sqlSession.close();
        in.close();
    }

猜你喜欢

转载自blog.csdn.net/weixin_47382783/article/details/113825046
今日推荐