zoukankan      html  css  js  c++  java
  • mybatis动态sql之遍历集合(学习foreach标签(初探))

    EmployeeMapperDynamicSql.java

    package com.gong.mybatis.mapper;
    
    import java.util.List;
    import java.util.Map;
    
    import org.apache.ibatis.annotations.MapKey;
    import org.apache.ibatis.annotations.Param;
    
    import com.gong.mybatis.bean.Employee;
    
    public interface EmployeeMapperDynamicSql {
        public List<Employee> getEmpByConditionIf(Employee employee);
        
        public List<Employee> getEmpByForeach(@Param("ids") List<Integer> ids);
    }

    EmployeeMapperDynamicSql.xml

    <?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.gong.mybatis.mapper.EmployeeMapperDynamicSql">
        <!-- 查询,要查那个就带上那个条件 -->
        <select id="getEmpByConditionIf" resultType="com.gong.mybatis.bean.Employee">
            select * from tbl_employee 
            <where>
                <choose>
                    <when test="id!=null">
                        id=#{id}
                    </when>
                    <when test="lastName!=null">
                        last_name like #{lastName}
                    </when>
                    <when test="email!=null">
                        email=#{email}
                    </when>
                    <otherwise>
                    </otherwise>
                </choose>
            </where>
        </select>
        
        <select id="getEmpByForeach" resultType="com.gong.mybatis.bean.Employee">
            select * from tbl_employee where id in
            <foreach collection="ids" item="item_id" separator="," open="(" close=")">
                #{item_id}
            </foreach>
        </select>
    </mapper>

    说明:

    • item:集合中元素迭代时的别名,该参数为必选。
    • index:在list和数组中,index是元素的序号,在map中,index是元素的key,item是元素的value,该参数可选
    • open:foreach代码的开始符号,一般是(和close=")"合用。常用在in(),values()时。该参数可选
    • separator:元素之间的分隔符,例如在in()的时候,separator=","会自动在元素中间用“,“隔开,避免手动输入逗号导致sql错误,如in(1,2,)这样。该参数可选。
    • close: foreach代码的关闭符号,一般是)和open="("合用。常用在in(),values()时。该参数可选。
    • collection: 要做foreach的对象,作为入参时,List对象默认用"list"代替作为键,数组对象有"array"代替作为键,Map对象没有默认的键。当然在作为入参时可以使用@Param("keyName")来设置键,设置keyName后,list,array将会失效。 除了入参这种情况外,还有一种作为参数对象的某个字段的时候。举个例子:如果User有属性List ids。入参是User对象,那么这个collection = "ids".如果User有属性Ids ids;其中Ids是个对象,Ids有个属性List id;入参是User对象,那么collection = "ids.id"

    也就是说整个sql语句是这样的:select * from tbl_employee where id in (1,2,3)

    注意的是我们在接口中定义了传入参数的名称,因此在collection中可以传入该名称。

    进行测试:

    package com.gong.mybatis.test;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Map;
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    import org.junit.Test;
    
    import com.gong.mybatis.bean.Employee;
    import com.gong.mybatis.mapper.EmployeeMapperDynamicSql;
    
    public class TestMybatis3 {
        
        public SqlSessionFactory getSqlSessionFactory() throws IOException {
            String resource = "mybatis-config.xml";
            InputStream is = Resources.getResourceAsStream(resource);
            return new SqlSessionFactoryBuilder().build(is);
        }
    
        @Test
        public void test() throws IOException {
            SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
            SqlSession openSession = sqlSessionFactory.openSession();
            try {
                EmployeeMapperDynamicSql mapper = openSession.getMapper(EmployeeMapperDynamicSql.class);
                List<Employee> es = mapper.getEmpByForeach(Arrays.asList(1,2,3));
                for(Employee e:es) {
                    System.out.println(e);
                }
                openSession.commit();
            } finally {
                openSession.close();
            }
            
        }
        
    }

    最终结果:

    DEBUG 01-21 15:31:16,176 ==>  Preparing: select * from tbl_employee where id in ( ? , ? , ? )   (BaseJdbcLogger.java:145) 
    DEBUG 01-21 15:31:16,241 ==> Parameters: 1(Integer), 2(Integer), 3(Integer)  (BaseJdbcLogger.java:145) 
    DEBUG 01-21 15:31:16,335 <==      Total: 3  (BaseJdbcLogger.java:145) 
    Employee [id=1, lastName=dema, gender=1, email=dema@qq.com, dept=null]
    Employee [id=2, lastName=jack, gender=1, email=675544321@qq.com, dept=null]
    Employee [id=3, lastName=小红, gender=0, email=xiaohong@qq.com, dept=null]
  • 相关阅读:
    032 Gradle 下载的依赖jar包在哪?
    031 can't rename root module,Android Studio修改项目名称
    030 Cannot resolve symbol'R' 问题解决汇总大全
    029 Android Studio层级显示目录文件
    028 You are about to commit CRLF line separators to the Git repository.It is recommended to set the core. autocrlf Git attribute to true to avoid line separator issues If you choose Fix and Comit ,
    027 【Android基础知识】Android Studio 编译慢及 Adb connection Error:远程主机强迫关闭了一个现有的连接
    026 Android Studio 和Gradle版版本对应关系
    025 Cause: org.jetbrains.plugins.gradle.tooling.util.ModuleComponentIdentifierIm
    024 Android Studio上传项目到Github 最全记录
    023 解决AndroidStudio下载gradle慢的问题
  • 原文地址:https://www.cnblogs.com/xiximayou/p/12222130.html
Copyright © 2011-2022 走看看