Mybatis学习笔记17 - sql标签和include标签

示例代码:

接口定义:
package com.mybatis.dao;

import com.mybatis.bean.Employee;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface EmployeeMapper {
    public void addEmps(@Param("emps") List<Employee> emps);
}


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.mybatis.dao.EmployeeMapper">
    <insert id="addEmps">
        insert into tbl_employee(
            <include refid="insertSql"/>
        )
        values
        <foreach collection="emps" item="emp" separator=",">
            (#{emp.lastName},#{emp.email},#{emp.gender},#{emp.dept.id})
        </foreach>
    </insert>


    <!--
        抽取可重用的sql片段。方便后面引用
        1、sql抽取:经常将要查询的列名,或者插入用的列名抽取出来方便引用
        2、include来引用已经抽取的sql:
        3、include还可以自定义一些property,sql标签内部就能使用自定义的属性
                include-property:取值的正确方式${prop},
                #{不能使用这种方式}
    -->

    <sql id="insertSql">
        last_name, email,gender, d_id
    </sql>
</mapper>


测试代码:
package com.mybatis.demo;

import com.mybatis.bean.Department;
import com.mybatis.bean.Employee;
import com.mybatis.dao.EmployeeMapper;
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 java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class MyTest {
    public SqlSessionFactory getSqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        return new SqlSessionFactoryBuilder().build(inputStream);
    }

    @Test
    public void test() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession openSession = sqlSessionFactory.openSession(true);
        try {
            EmployeeMapper mapper = openSession.getMapper(EmployeeMapper.class);
            List<Employee> emps = new ArrayList<Employee>();
            emps.add(new Employee(null, "sujun", "sujun@qq.com", 1, new Department(1)));
            emps.add(new Employee(null, "minmin", "minmin@qq.com", 1, new Department(2)));
            mapper.addEmps(emps);
        } finally {
            openSession.close();
        }
    }
}

 

posted on 2019-02-04 19:32  lina2014  阅读(892)  评论(0编辑  收藏  举报

导航