[Mybatis from entry to actual combat tutorial] Chapter 4 Mybatis input mapping, output mapping and dynamic SQL detailed explanation

4. Mybatis Mapper configuration file

The Sql for operating the database is defined in the mapper.xml mapping file. Each Sql is a statement, and the mapping file is the core of MyBatis.

4.1 parameterType input mapping

    parameterType configures the type of the input parameter.

4.1.1 Table structure

CREATE TABLE `users`  (
  `id` int(11) PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(20),
  `password` varchar(50),
  `realname` varchar(20)
);

INSERT INTO `users` VALUES (1, 'admin', '123456', '管理员');
INSERT INTO `users` VALUES (2, 'tom', '123', '汤姆');
INSERT INTO `users` VALUES (3, 'jerry', '456', '杰瑞');
INSERT INTO `users` VALUES (4, 'zhangsan', '111', '张三');
INSERT INTO `users` VALUES (5, 'lisi', '222', '李四');

4.1.2 Entity class

package com.newcapec.entity;

public class Users {

    private Integer id;
    private String username;
    private String password;
    private String realname;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getRealname() {
        return realname;
    }

    public void setRealname(String realname) {
        this.realname = realname;
    }

    @Override
    public String toString() {
        return "Users{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", realname='" + realname + '\'' +
                '}';
    }
}

4.1.3 Simple types

    Java basic data types and packaging classes, String string type.

mapper interface:

package com.newcapec.mapper;

import com.newcapec.entity.Users;

import java.util.List;

public interface UsersMapper {
    List<Users> selectByRealname(String realname);
}

mapper file:

<?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.newcapec.mapper.UsersMapper">

    <select id="selectByRealname" parameterType="java.lang.String" resultType="com.newcapec.entity.Users">
        select id,username,password,realname from users where realname like concat('%',#{realname},'%')
    </select>
</mapper>

test:

package com.newcapec;

import com.newcapec.entity.Users;
import com.newcapec.mapper.UsersMapper;
import com.newcapec.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class ParameterTypeTest {

    @Test
    public void testSimpleParam() {
        SqlSession sqlSession = MybatisUtil.getSession();
        UsersMapper usersMapper = sqlSession.getMapper(UsersMapper.class);
        List<Users> list = usersMapper.selectByRealname("张");
        for (Users users : list) {
            System.out.println(users);
        }
        sqlSession.close();
    }
}

4.1.4 Entity class or custom type

    During development, the query conditions are passed through the entity class or pojo type. The query conditions are comprehensive query conditions, including not only the query conditions in the entity class but also other query conditions. At this time, you can use the wrapper object to pass the input parameters.

  • custom type

Pagination class:

package com.newcapec.entity;

/**
 * 分页类
 */
public class Page {

    //当前页码
    private Integer pageNum = 1;
    //每页条数
    private Integer pageSize = 3;
    //总页数: 总记录数/每页条数,除不尽+1
    private Integer pages;
    //总记录数
    private Integer total;

    /**
     * mysql
     * 起始偏移量:(当前页码-1)*每页条数
     */
    private Integer offset;

    /**
     * oracle
     * 起始条数:(当前页码-1)*每页条数+1
     * 结束条数: 当前页码*每页条数
     */
    private Integer start;
    private Integer end;

    public Integer getPageNum() {
        return pageNum;
    }

    public void setPageNum(Integer pageNum) {
        this.pageNum = pageNum;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Integer getPages() {
        return getTotal() % getPageSize() == 0 ? getTotal() / getPageSize() : getTotal() / getPageSize() + 1;
    }

    public void setPages(Integer pages) {
        this.pages = pages;
    }

    public Integer getTotal() {
        return total;
    }

    public void setTotal(Integer total) {
        this.total = total;
    }

    public Integer getOffset() {
        return (getPageNum() - 1) * getPageSize();
    }

    public void setOffset(Integer offset) {
        this.offset = offset;
    }

    public Integer getStart() {
        return (getPageNum() - 1) * getPageSize() + 1;
    }

    public void setStart(Integer start) {
        this.start = start;
    }

    public Integer getEnd() {
        return getPageNum() * getPageSize();
    }

    public void setEnd(Integer end) {
        this.end = end;
    }
}

Composite class: UsersQuery

package com.newcapec.entity;

/**
 * 多条件查询复合类
 */
public class UsersQuery {

    private Users users;
    private Page page;

    public Users getUsers() {
        return users;
    }

    public void setUsers(Users users) {
        this.users = users;
    }

    public Page getPage() {
        return page;
    }

    public void setPage(Page page) {
        this.page = page;
    }
}
  • mapper interface
List<Users> selectByPage(Page page);

List<Users> selectByRealnameAndPage(UsersQuery usersQuery);
  • mapper file
<select id="selectByPage" parameterType="com.newcapec.entity.Page" resultType="com.newcapec.entity.Users">
    select id,username,password,realname from users order by id limit #{offset}, #{pageSize}
</select>

<select id="selectByRealnameAndPage" parameterType="com.newcapec.entity.UsersQuery" resultType="com.newcapec.entity.Users">
    select id,username,password,realname from users
    where realname like concat('%',#{users.realname},'%')
    order by id limit #{page.offset}, #{page.pageSize}
</select>
  • test
@Test
public void testClassParam1() {
    SqlSession sqlSession = MybatisUtil.getSession();
    UsersMapper usersMapper = sqlSession.getMapper(UsersMapper.class);
    Page page = new Page();
    page.setPageNum(1);

    System.out.println("mysql起始偏移量:" + page.getOffset());
    System.out.println("起始条数:" + page.getStart());
    System.out.println("结束条数:" + page.getEnd());
    List<Users> list = usersMapper.selectByPage(page);
    for (Users users : list) {
        System.out.println(users);
    }
    sqlSession.close();
}

@Test
public void testPojoParam2() {
    SqlSession sqlSession = MybatisUtil.getSession();
    UsersMapper usersMapper = sqlSession.getMapper(UsersMapper.class);
    Page page = new Page();
    page.setPageNum(1);

    Users users = new Users();
    users.setRealname("张");
    UsersQuery usersQuery = new UsersQuery();
    usersQuery.setPage(page);
    usersQuery.setUsers(users);

    List<Users> list = usersMapper.selectByRealnameAndPage(usersQuery);
    for (Users u : list) {
        System.out.println(u);
    }
    sqlSession.close();
}

4.1.5 Map type

mapper interface:

List<Users> selectUseMap(Map<String, Object> map);

mapper file:

<select id="selectUseMap" parameterType="java.util.HashMap" resultType="com.newcapec.entity.Users">
    select id,username,password,realname from users
    where realname like concat('%',#{name},'%')
    order by id limit #{begin}, #{size}
</select>

test:

@Test
public void testMapParam() {
    SqlSession sqlSession = MybatisUtil.getSession();
    UsersMapper usersMapper = sqlSession.getMapper(UsersMapper.class);
    Map<String, Object> map = new HashMap<>();
    map.put("name", "李");
    map.put("size", 5);
    map.put("begin", 0);

    List<Users> list = usersMapper.selectUseMap(map);
    for (Users u : list) {
        System.out.println(u);
    }
    sqlSession.close();
}

4.1.6 Multiple Input Parameters

    Multiple input parameters are allowed in MyBatis, which can be annotated with @Param.

    This approach is similar to the input parameter of the Map type, where the value attribute of the @Param annotation is the key of the Map, and the corresponding value can be obtained through ognl in the mapping file, and the parameterType does not need to specify a type.

mapper interface:

Users login(@Param("uname") String username, @Param("pwd") String password);

mapper file:

<select id="login" parameterType="java.util.HashMap" resultType="com.newcapec.entity.Users">
    select id,username,password,realname from users
    where username=#{uname} and password=#{pwd}
</select>

test:

@Test
public void testMultiParam() {
    SqlSession sqlSession = MybatisUtil.getSession();
    UsersMapper usersMapper = sqlSession.getMapper(UsersMapper.class);

    Users users = usersMapper.login("jerry", "456");
    System.out.println(users);
    sqlSession.close();
}

4.2 resultType output mapping

4.2.1 Table structure

CREATE TABLE `person`  (
  `id` int(11) PRIMARY KEY AUTO_INCREMENT,
  `person_name` varchar(20),
  `person_age` int(4),
  `person_address` varchar(50)
);

INSERT INTO `person` VALUES (1, '曹操', 40, '洛阳');
INSERT INTO `person` VALUES (2, '刘备', 38, '成都');
INSERT INTO `person` VALUES (3, '孙权', 29, '杭州');
INSERT INTO `person` VALUES (4, '关羽', 35, '荆州');
INSERT INTO `person` VALUES (5, '张飞', 32, '成都');
INSERT INTO `person` VALUES (6, '曹仁', 28, '许都');

4.2.2 Entity class

package com.newcapec.entity;

public class Person {

    private Integer id;
    private String personName;
    private Integer personAge;
    private String personAddress;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getPersonName() {
        return personName;
    }

    public void setPersonName(String personName) {
        this.personName = personName;
    }

    public Integer getPersonAge() {
        return personAge;
    }

    public void setPersonAge(Integer personAge) {
        this.personAge = personAge;
    }

    public String getPersonAddress() {
        return personAddress;
    }

    public void setPersonAddress(String personAddress) {
        this.personAddress = personAddress;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", personName='" + personName + '\'' +
                ", personAge=" + personAge +
                ", personAddress='" + personAddress + '\'' +
                '}';
    }
}

4.2.3 Simple types

    The query result set has only one row and one column, and simple types can be used for output mapping.

mapper interface:

package com.newcapec.mapper;

public interface PersonMapper {
    // 查询Person的总数量
    Integer selectCount();
}

mapper file:

<?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.newcapec.mapper.PersonMapper">

    <select id="selectCount" resultType="java.lang.Integer">
        select count(1) from person
    </select>
</mapper>

test:

public class ResultTypeTest {

    @Test
    public void testSimpleResult() {
        SqlSession sqlSession = MybatisUtil.getSession();
        PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);

        int total = personMapper.selectCount();
        System.out.println("总记录数:" + total);
        sqlSession.close();
    }
}

4.2.4 Entity class objects and lists

    Regardless of whether the output entity class is a single object or a list (the list includes entity class objects), the type specified by resultType in mapper.xml is the same. In the original Dao method, the return value is distinguished by the selectOne and selectList
methods A single object or a list of collections, and in the mapper proxy, are distinguished by the method return value defined in the interface.

mapper interface:

Person selectById(Integer id);

List<Person> selectAll();

mapper file:

<select id="selectById" parameterType="java.lang.Integer" resultType="com.newcapec.entity.Person">
    select id,person_name personName,person_age personAge,person_address personAddress from person where id=#{id}
</select>

<select id="selectAll" resultType="com.newcapec.entity.Person">
    select id,person_name personName,person_age personAge,person_address personAddress from person
</select>

test:

@Test
public void testResultType1() {
    SqlSession sqlSession = MybatisUtil.getSession();
    PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);

    Person person = personMapper.selectById(1);
    System.out.println(person);
    sqlSession.close();
}

@Test
public void testResultType2() {
    SqlSession sqlSession = MybatisUtil.getSession();
    PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);

    List<Person> list = personMapper.selectAll();
    for (Person person : list) {
        System.out.println(person);
    }
    sqlSession.close();
}

4.2.5 resultMap

  • resultType can specify that the query result is mapped to an entity class, but the attribute name of the entity class must be consistent with the column name of the SQL query to be successfully mapped. Of course, if you enable underscore to camel case or Sql sets the column alias, it can also be automatically mapped.

  • If the SQL query field name is inconsistent with the attribute name of the entity class, you can use the resultMap to make a corresponding relationship between the field name and the attribute name, and the resultMap will essentially map the query result to the entity class object.

  • resultMap can realize the mapping of query results to composite entity classes, such as including entity classes and lists in the query result mapping object to realize one-to-one query and one-to-many query.

mapper interface:

List<Person> select();

mapper file:

    Use resultMap as the output mapping type of statement.

<resultMap id="selectResultMap" type="com.newcapec.entity.Person">
    <id property="id" column="id"/>
    <result property="personName" column="person_name"/>
    <result property="personAge" column="person_age"/>
    <result property="personAddress" column="person_address"/>
</resultMap>
<select id="select" resultMap="selectResultMap">
    select id,person_name,person_age,person_address from person
</select>
  • resultType: automatic mapping

  • resultMap: manual mapping

    • id: unique identifier, name;

    • type: manually mapped java type

    • Sub-label <id/>Configure the correspondence between the primary key in the database table and the attribute in the entity class

    • Sub-tags <result/>Configure the correspondence between common fields in database tables and attributes in entity classes

      • property: the name of the member variable in the entity class

      • column: the name of the field in the result set

      • javaType: the type of the entity class member variable, which is automatically recognized by mybaits, and it is not necessary to configure

      • jdbcType: the type of the table field, which is automatically recognized by mybaits, and can not be configured

      • typeHandler: custom type handler, relatively less used

test:

@Test
public void testResultMap() {
    SqlSession sqlSession = MybatisUtil.getSession();
    PersonMapper personMapper = sqlSession.getMapper(PersonMapper.class);

    List<Person> list = personMapper.select();
    for (Person person : list) {
        System.out.println(person);
    }
    sqlSession.close();
}

4.3 Dynamic SQL

4.3.1 What is dynamic SQL

    Dynamic Sql refers to the flexible operation of Sql statements by the MyBatis core, judgment through expressions, and flexible splicing and assembly of Sql.
    
    For example:
        we want to query employee information with M in the name and higher than 1000;
        maybe sometimes we need to query without conditions;
        maybe sometimes we need fuzzy queries;
        sometimes we need to query based on multiple conditions;
        dynamic SQL can help us solve these questions;

    Dynamic splicing of sql is realized through various label methods provided by mybatis.

4.3.2 if tag

    Judgment label, when the parameter meets the judgment condition, the SQL statement is spliced.

Entity class:

package com.newcapec.entity;

import java.util.Date;

public class Emp {

    private Integer empno;
    private String ename;
    private String job;
    private Integer mgr;
    private Date hiredate;
    private Double sal;
    private Double comm;
    private Integer deptno;
    private String gender;

    public Integer getEmpno() {
        return empno;
    }

    public void setEmpno(Integer empno) {
        this.empno = empno;
    }

    public String getEname() {
        return ename;
    }

    public void setEname(String ename) {
        this.ename = ename;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public Integer getMgr() {
        return mgr;
    }

    public void setMgr(Integer mgr) {
        this.mgr = mgr;
    }

    public Date getHiredate() {
        return hiredate;
    }

    public void setHiredate(Date hiredate) {
        this.hiredate = hiredate;
    }

    public Double getSal() {
        return sal;
    }

    public void setSal(Double sal) {
        this.sal = sal;
    }

    public Double getComm() {
        return comm;
    }

    public void setComm(Double comm) {
        this.comm = comm;
    }

    public Integer getDeptno() {
        return deptno;
    }

    public void setDeptno(Integer deptno) {
        this.deptno = deptno;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "empno=" + empno +
                ", ename='" + ename + '\'' +
                ", job='" + job + '\'' +
                ", mgr=" + mgr +
                ", hiredate=" + hiredate +
                ", sal=" + sal +
                ", comm=" + comm +
                ", deptno=" + deptno +
                ", gender='" + gender + '\'' +
                '}';
    }
}

mapper interface:

public interface EmpMapper {
    
    List<Emp> selectUseIf(Emp emp);
}

mapper file:

<select id="selectUseIf" parameterType="com.newcapec.entity.Emp" resultType="com.newcapec.entity.Emp">
    select empno,ename,job,mgr,hiredate,sal,comm,deptno from emp
    where
    <!--
		注意:判断条件中使用的变量为实体类或输入参数的属性
			 空字符串的判断仅能使用在字符串类型的属性中
	-->
    <if test="ename != null and ename != ''">
        ename like concat('%',#{ename},'%')
    </if>
    <if test="sal != null">
        and sal=#{sal}
    </if>
    <if test="deptno != null">
        and deptno=#{deptno}
    </if>
</select>

test:

/*
 * 动态sql测试
 */
public class DynamicSqlTest {

    @Test
    public void testIf() {
        SqlSession sqlSession = MybatisUtil.getSession();
        EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);

        Emp emp = new Emp();
        emp.setEname("S");
        emp.setSal(1300.0);
        emp.setDeptno(20);

        List<Emp> list = empMapper.selectUseIf(emp);
        for (Emp e : list) {
            System.out.println(e);
        }
        sqlSession.close();
    }
}

4.3.3 where tag

    The where tag replaces the where keyword.
        1. When all the conditions in the where tag are not satisfied, the where keyword will not be spliced. As long as one condition is true, the where keyword will be spliced ​​in the SQL statement.
        2. The where tag will automatically remove the and or or keywords in the condition head.

mapper interface:

List<Emp> selectUseWhere(Emp emp);

mapper file:

<select id="selectUseWhere" parameterType="com.newcapec.entity.Emp" resultType="com.newcapec.entity.Emp">
    select empno,ename,job,mgr,hiredate,sal,comm,deptno from emp
    <where>
        <if test="ename != null and ename != ''">
            ename like concat('%',#{ename},'%')
        </if>
        <if test="sal != null">
            and sal=#{sal}
        </if>
        <if test="deptno != null">
            and deptno=#{deptno}
        </if>
    </where>
</select>

test:

@Test
public void testWhere() {
    SqlSession sqlSession = MybatisUtil.getSession();
    EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);

    Emp emp = new Emp();
    emp.setEname("S");
    emp.setSal(1300.0);
    emp.setDeptno(20);

    List<Emp> list = empMapper.selectUseWhere(emp);
    for (Emp e : list) {
        System.out.println(e);
    }
    sqlSession.close();
}

4.3.4 set label

    set tag, instead of the set keyword.
        1. When all the conditions in the set tag are not satisfied, the set keyword will not be spliced. As long as one condition is true, the set keyword will be spliced ​​in the SQL statement.
        2. Note: If the content contained in the set is empty, an error will occur in the SQL statement.
        3. The set tag will automatically remove any irrelevant commas at the end of the condition.

mapper interface:

void updateUseSet(Emp emp);

mapper file:

<update id="updateUseSet" parameterType="com.newcapec.entity.Emp">
    update emp
    <set>
        <if test="ename != null">
            ename=#{ename},
        </if>
        <if test="job != null">
            job=#{job},
        </if>
        <if test="mgr != null">
            mgr=#{mgr},
        </if>
        <if test="hiredate != null">
            hiredate=#{hiredate},
        </if>
        <if test="sal != null">
            sal=#{sal},
        </if>
        <if test="comm != null">
            comm=#{comm},
        </if>
        <if test="deptno != null">
            deptno=#{deptno},
        </if>
    </set>
    where empno=#{empno}
</update>

test:

@Test
public void testSet() {
    SqlSession sqlSession = MybatisUtil.getSession();
    EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);

    Emp emp = new Emp();
    emp.setEmpno(7938);
    emp.setEname("JACK");
    emp.setJob("MANAGER");
    emp.setMgr(7844);
    emp.setSal(5600.0);
    emp.setComm(1200.0);
    emp.setHiredate(new Date());
    emp.setDeptno(30);
    empMapper.updateUseSet(emp);
    sqlSession.commit();
    sqlSession.close();
}

4.3.5 trim label

Trim tag attribute analysis:

  • prefix: prefix, including some characters before the content.

  • suffix: suffix, including some characters after the content.

  • prefixOverrides: Eliminate some characters before the included content.

  • suffixOverrides: Remove some characters after the included content.

mapper interface:

void insertUseTrim(Emp emp);

mapper file:

<insert id="insertUseTrim" parameterType="com.newcapec.entity.Emp">
    insert into emp
    <trim prefix="(" suffix=")" suffixOverrides=",">
        <if test="ename != null">
            ename,
        </if>
        <if test="job != null">
            job,
        </if>
        <if test="mgr != null">
            mgr,
        </if>
        <if test="hiredate != null">
            hiredate,
        </if>
        <if test="sal != null">
            sal,
        </if>
        <if test="comm != null">
            comm,
        </if>
        <if test="deptno != null">
            deptno,
        </if>
    </trim>
    <trim prefix=" values(" suffix=")" suffixOverrides=",">
        <if test="ename != null">
            #{ename},
        </if>
        <if test="job != null">
            #{job},
        </if>
        <if test="mgr != null">
            #{mgr},
        </if>
        <if test="hiredate != null">
            #{hiredate},
        </if>
        <if test="sal != null">
            #{sal},
        </if>
        <if test="comm != null">
            #{comm},
        </if>
        <if test="deptno != null">
            #{deptno},
        </if>
    </trim>
</insert>

test:

@Test
public void testTrim() {
    SqlSession sqlSession = MybatisUtil.getSession();
    EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);

    Emp emp = new Emp();
    emp.setEname("CHRIS");
    emp.setJob("CLERK");
    emp.setMgr(1);
    emp.setSal(3400.0);
    emp.setComm(800.0);
    emp.setHiredate(new Date());
    emp.setDeptno(10);

    empMapper.insertUseTrim(emp);
    sqlSession.commit();
    sqlSession.close();
}

Instead of where tag:

<select id="selectUseTrim" parameterType="com.newcapec.entity.Emp" resultType="com.newcapec.entity.Emp">
    select empno,ename,job,mgr,hiredate,sal,comm,deptno from emp
    <trim prefix="where" prefixOverrides="and|or">
        <if test="ename != null and ename != ''">
            ename like concat('%',#{ename},'%')
        </if>
        <if test="sal != null">
            and sal=#{sal}
        </if>
        <if test="deptno != null">
            and deptno=#{deptno}
        </if>
    </trim>
</select>

Instead of set tags:

<update id="updateUseTrim" parameterType="com.newcapec.entity.Emp">
    update emp
    <trim prefix="set" suffixOverrides=",">
        <if test="ename != null">
            ename=#{ename},
        </if>
        <if test="job != null">
            job=#{job},
        </if>
        <if test="mgr != null">
            mgr=#{mgr},
        </if>
        <if test="hiredate != null">
            hiredate=#{hiredate},
        </if>
        <if test="sal != null">
            sal=#{sal},
        </if>
        <if test="comm != null">
            comm=#{comm},
        </if>
        <if test="deptno != null">
            deptno=#{deptno},
        </if>
    </trim>
    where empno=#{empno}
</update>

4.3.6 foreach tag

    Pass an array or list to SQL, and MyBatis uses foreach to parse.

Attribute resolution:

  • collection: The name of the array or collection object to traverse.

    • SQL only accepts an array parameter. At this time, the name of the SQL parsing parameter MyBatis is fixed as array.

    • SQL only accepts a List parameter. At this time, the name of the SQL parsing parameter MyBatis is fixed as list.

    • If an attribute of an entity class or a custom type is passed to an SQL array or List collection, the name of the parameter is the name of the attribute in the entity class or custom type.

  • index: The subscript of the array.

  • item: in each traversal generated object.

  • open: The concatenated string at the beginning of traversal.

  • close: The concatenated string at the end of the traversal.

  • separator: The string that needs to be concatenated in the two objects traversed.

mapper interface:

void deleteUseForeach(Integer[] ids);

void insertUseForeach(List<Emp> empList);

mapper file:

<delete id="deleteUseForeach" parameterType="java.lang.Integer">
    <!--delete from emp where empno in (1,2,3,4)-->
    delete from emp where empno in
    <foreach collection="array" open="(" close=")" separator="," item="id">
        #{id}
    </foreach>
</delete>

<insert id="insertUseForeach" parameterType="com.newcapec.entity.Emp">
    insert into emp(ename,job,mgr,hiredate,sal,comm,deptno) values
    <foreach collection="list" separator="," item="emp">
        (#{emp.ename},#{emp.job},#{emp.mgr},#{emp.hiredate},#{emp.sal},#{emp.comm},#{emp.deptno})
    </foreach>
</insert>

test:

@Test
public void testForeach() {
    SqlSession sqlSession = MybatisUtil.getSession();
    EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);

    empMapper.deleteUseForeach(new Integer[]{1, 2, 3, 4});
    sqlSession.commit();
    sqlSession.close();
}

@Test
public void testForeach2() {
    SqlSession sqlSession = MybatisUtil.getSession();
    EmpMapper empMapper = sqlSession.getMapper(EmpMapper.class);

    List<Emp> empList = new ArrayList<>();
    for (int i = 1; i <= 3; i++) {
        Emp emp = new Emp();
        emp.setEname("TOM" + i);
        emp.setJob("CLERK" + i);
        emp.setMgr(1);
        emp.setSal(4567.0);
        emp.setComm(123.0);
        emp.setHiredate(new Date());
        emp.setDeptno(10);
        empList.add(emp);
    }
    empMapper.insertUseForeach(empList);
    //sqlSession.commit();
    sqlSession.close();
}

4.3.7 choose label

    The combination of choose tag, when tag, and otherwise tag is similar to if-else-if judgment.

<select id="">
    select...
    <choose>
        <when test="">

        </when>
        <when test="">

        </when>
        <otherwise>

        </otherwise>
    </choose>
</select>

4.3.8 SQL Fragments

    Extract the implemented dynamic SQL judgment code block to form a SQL fragment, which can be referenced in other statements, which is convenient for programmers to develop.

    Note: Do not include where tags in SQL fragments.

<sql id="feildSql">
    empno,ename,job,mgr,hiredate,sal,comm,deptno
</sql>

<sql id="whereSql">
    <if test="ename != null and ename != ''">
        ename like concat('%',#{ename},'%')
    </if>
    <if test="sal != null">
        and sal=#{sal}
    </if>
    <if test="deptno != null">
        and deptno=#{deptno}
    </if>
</sql>

<select id="selectUseSql" parameterType="com.newcapec.entity.Emp" resultType="com.newcapec.entity.Emp">
    select
    <include refid="feildSql"></include>
    from emp
    <where>
        <include refid="whereSql"></include>
    </where>
</select>

Guess you like

Origin blog.csdn.net/ligonglanyuan/article/details/124319848