Mybatis (三)

1 Mybatis的动态SQL简介

  • 动态SQL是Mybatis强大的特性之一,极大的简化我们拼接SQL的操作。
  • 动态SQL元素和使用JSTL或其他类似基于XML的文本处理器相似。
  • Mybatis采用功能强大的OGNL表达式来简化操作。
    • if
    • choose when otherwise
    • trim where set
    • foreach  

2 if标签

  • 示例:

    • EmployeeMapper.java  
package com.xuweiwei.mybatis.mapper;

import com.xuweiwei.mybatis.pojo.Employee;

import java.util.List;

public interface EmployeeMapper {

    public List<Employee> getEmployeeByIf(Employee employee);

}
    • EmployeeMapper.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.xuweiwei.mybatis.mapper.EmployeeMapper">

    <select id="getEmployeeByIf" parameterType="com.xuweiwei.mybatis.pojo.Employee" resultType="com.xuweiwei.mybatis.pojo.Employee">
        SELECT id,last_name,gender,email
        FROM employee
        WHERE
        <!--
            if标签用来判断,和jstl中的c:if功能类似
        -->
        <if test="id != null" >
            id = #{id}
        </if>
        <if test="lastName != null and lastName.trim() != ‘‘">
            and last_name like #{lastName}
        </if>
        <if test="gender != null and gender.trim() != ‘‘">
            and gender = #{gender}
        </if>
        <if test="email != null and email.trim() != ‘‘">
            and email = #{email}
        </if>

    </select>

</mapper>
  • 但是,一旦id为null,那么就会报错。

  • 在where后面加1=1,然后在id前面加and id = #{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 namespace="com.xuweiwei.mybatis.mapper.EmployeeMapper">

    <select id="getEmployeeByIf" parameterType="com.xuweiwei.mybatis.pojo.Employee" resultType="com.xuweiwei.mybatis.pojo.Employee">
        SELECT id,last_name,gender,email
        FROM employee
        WHERE  1=1
        <!--
            if标签用来判断,和jstl中的c:if功能类似
        -->
        <if test="id != null" >
            and id = #{id}
        </if>
        <if test="lastName != null and lastName.trim() != ‘‘">
            and last_name like #{lastName}
        </if>
        <if test="gender != null and gender.trim() != ‘‘">
            and gender = #{gender}
        </if>
        <if test="email != null and email.trim() != ‘‘">
            and email = #{email}
        </if>

    </select>

</mapper>
  • 但是这种方法,太繁琐了,有些人并不一定遵守啊。所以,针对这种情况,可以使用<where>标签,它可以自动将多余的and去掉。

3 where标签

  • 示例:

    • EmployeeMapper.java  
package com.xuweiwei.mybatis.mapper;

import com.xuweiwei.mybatis.pojo.Employee;

import java.util.List;

public interface EmployeeMapper {

    public List<Employee> getEmployeeByIf(Employee employee);

}
    • EmployeeMapper.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.xuweiwei.mybatis.mapper.EmployeeMapper">

    <select id="getEmployeeByIf" parameterType="com.xuweiwei.mybatis.pojo.Employee" resultType="com.xuweiwei.mybatis.pojo.Employee">
        SELECT id,last_name,gender,email
        FROM employee
        <!--
            where 标签 可以将多余的and去掉
        -->
        <where>
            <!--
           if标签用来判断,和jstl中的c:if功能类似
       -->
            <if test="id != null" >
                id = #{id}
            </if>
            <if test="lastName != null and lastName.trim() != ‘‘">
                and last_name like #{lastName}
            </if>
            <if test="gender != null and gender.trim() != ‘‘">
                and gender = #{gender}
            </if>
            <if test="email != null and email.trim() != ‘‘">
                and email = #{email}
            </if>
        </where>

    </select>

</mapper>
    • 测试  
package com.xuweiwei.mybatis.test;

import com.xuweiwei.mybatis.mapper.EmployeeMapper;
import com.xuweiwei.mybatis.pojo.Employee;
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.List;

public class MybatisTest {
    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {

            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Employee emp = new Employee();
            emp.setId(3);
            emp.setEmail("[email protected]");
            List<Employee> employees = employeeMapper.getEmployeeByIf(emp);
            System.out.println(employees);

        } finally {
            session.close();
        }
    }

}
  • 但是,这样也有问题,有人喜欢将and放在每个条件的最后,请看下面的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.xuweiwei.mybatis.mapper.EmployeeMapper">

    <select id="getEmployeeByIf" parameterType="com.xuweiwei.mybatis.pojo.Employee" resultType="com.xuweiwei.mybatis.pojo.Employee">
        SELECT id,last_name,gender,email
        FROM employee
        <!--
            where 标签 可以将多余的and去掉
        -->
        <where>
            <!--
           if标签用来判断,和jstl中的c:if功能类似
       -->
            <if test="id != null" >
                id = #{id} and
            </if>
            <if test="lastName != null and lastName.trim() != ‘‘">
                 last_name like #{lastName} and
            </if>
            <if test="gender != null and gender.trim() != ‘‘">
                 gender = #{gender} and
            </if>
            <if test="email != null and email.trim() != ‘‘">
                 email = #{email} and
            </if>
        </where>

    </select>

</mapper>
  • 此时,Mybatis内心是崩溃的,你们这些愚蠢的人类,就是瞎折腾。那么此时可以使用trim标签。

4 trim标签

  • 示例:

    • EmployeeMapper.java  
package com.xuweiwei.mybatis.mapper;

import com.xuweiwei.mybatis.pojo.Employee;

import java.util.List;

public interface EmployeeMapper {

    public List<Employee> getEmployeeByIf(Employee employee);

}
    • EmployeeMapper.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.xuweiwei.mybatis.mapper.EmployeeMapper">

    <select id="getEmployeeByIf" parameterType="com.xuweiwei.mybatis.pojo.Employee"
            resultType="com.xuweiwei.mybatis.pojo.Employee">
        SELECT id,last_name,gender,email
        FROM employee
        <!--
            trim标签
            prefix:在trim标签范围内的所有语句,前面加上prefix属性对应的值
            prefixOverrides:将在trim标签范围内的所有语句前面多余的和prefixOverrides相等的值去掉
            suffix:和prefix相反
            suffixOverrides:和prefixOverrides相反
        -->
        <trim prefix="where" suffixOverrides="and">
            <!--
                if标签用来判断,和jstl中的c:if功能类似
            -->
            <if test="id != null">
                id = #{id} and
            </if>
            <if test="lastName != null and lastName.trim() != ‘‘">
                last_name like #{lastName} and
            </if>
            <if test="gender != null and gender.trim() != ‘‘">
                gender = #{gender} and
            </if>
            <if test="email != null and email.trim() != ‘‘">
                email = #{email} and
            </if>
        </trim>

    </select>

</mapper>
    • 测试  
package com.xuweiwei.mybatis.test;

import com.xuweiwei.mybatis.mapper.EmployeeMapper;
import com.xuweiwei.mybatis.pojo.Employee;
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.List;

public class MybatisTest {
    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {

            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Employee emp = new Employee();
            emp.setId(3);
            emp.setEmail("[email protected]");
            List<Employee> employees = employeeMapper.getEmployeeByIf(emp);
            System.out.println(employees);

        } finally {
            session.close();
        }
    }

}
  • 当然,针对2if标签所面对的问题,也可以使用trim来解决,请看如下的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.xuweiwei.mybatis.mapper.EmployeeMapper">

    <select id="getEmployeeByIf" parameterType="com.xuweiwei.mybatis.pojo.Employee"
            resultType="com.xuweiwei.mybatis.pojo.Employee">
        SELECT id,last_name,gender,email
        FROM employee
        <!--
            trim标签
            prefix:在trim标签范围内的所有语句,前面加上prefix属性对应的值
            prefixOverrides:将在trim标签范围内的所有语句前面多余的和prefixOverrides相等的值去掉
            suffix:和prefix相反
            suffixOverrides:和prefixOverrides相反
        -->
        <trim prefix="where" prefixOverrides="and">
            <!--
                if标签用来判断,和jstl中的c:if功能类似
            -->
            <if test="id != null">
                id = #{id}
            </if>
            <if test="lastName != null and lastName.trim() != ‘‘">
                and last_name like #{lastName}
            </if>
            <if test="gender != null and gender.trim() != ‘‘">
                and gender = #{gender}
            </if>
            <if test="email != null and email.trim() != ‘‘">
                and email = #{email}
            </if>
        </trim>

    </select>

</mapper>

5 choose-when-otherwise标签(选择分支)

  • 示例:查询雇员信息,如果id不是null,就用id查询,以此类推。

    • EmployeeMapper.java  
package com.xuweiwei.mybatis.mapper;

import com.xuweiwei.mybatis.pojo.Employee;

import java.util.List;

public interface EmployeeMapper {

    public List<Employee> getEmployeeByIf(Employee employee);

}
    • EmployeeMapper.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.xuweiwei.mybatis.mapper.EmployeeMapper">

    <select id="getEmployeeByIf" parameterType="com.xuweiwei.mybatis.pojo.Employee"
            resultType="com.xuweiwei.mybatis.pojo.Employee">
        SELECT id,last_name,gender,email
        FROM employee
        <where>
            <choose>
                <when test="id != null">
                    id = #{id}
                </when>
                <when test="lastName != null">
                    last_name like #{lastName}
                </when>
                <when test="gender != null">
                    gender = #{gender}
                </when>
                <otherwise>
                    email = #{email}
                </otherwise>
            </choose>
        </where>
    </select>

</mapper>

6 set标签

  • 示例:根据指定的条件根据雇员信息

    • EmployeeMapper.java    
package com.xuweiwei.mybatis.mapper;

import com.xuweiwei.mybatis.pojo.Employee;

public interface EmployeeMapper {

    public boolean updateEmployee(Employee employee);

}
    • EmployeeMapper.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.xuweiwei.mybatis.mapper.EmployeeMapper">

   <update id="updateEmployee" parameterType="com.xuweiwei.mybatis.pojo.Employee">
       UPDATE employee
       SET
       <if test="lastName != null">
           last_name = #{lastName},
       </if>
       <if test="gender != null">
           gender = #{gender},
       </if>
       <if test="email != null">
           email = #{email}
       </if>
       <where>
           id = #{id}
       </where>

   </update>

</mapper>
    • 测试  
package com.xuweiwei.mybatis.test;

import com.xuweiwei.mybatis.mapper.EmployeeMapper;
import com.xuweiwei.mybatis.pojo.Employee;
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;

public class MybatisTest {
    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {

            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Employee emp = new Employee();
            emp.setGender("男");
            emp.setId(3);
            emp.setEmail("[email protected]");
            emp.setLastName("许飞");
            boolean flag  = employeeMapper.updateEmployee(emp);
            System.out.println(flag);

        } finally {
            session.close();
        }
    }

}
  • 这样,看似没有问题,如果一旦email为null的话,那么数据库就会发出错误

    • 测试代码如下  
package com.xuweiwei.mybatis.test;

import com.xuweiwei.mybatis.mapper.EmployeeMapper;
import com.xuweiwei.mybatis.pojo.Employee;
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;

public class MybatisTest {
    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {

            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Employee emp = new Employee();
            emp.setGender("男");
            emp.setId(3);
            emp.setLastName("许飞");
            boolean flag  = employeeMapper.updateEmployee(emp);
            System.out.println(flag);

        } finally {
            session.close();
        }
    }

}

  

  • 所以,使用SET标签,这样Mybatis就会将多余的逗号(,)干掉
<?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.xuweiwei.mybatis.mapper.EmployeeMapper">

   <update id="updateEmployee" parameterType="com.xuweiwei.mybatis.pojo.Employee">
       UPDATE employee
       <set>
           <if test="lastName != null">
               last_name = #{lastName},
           </if>
           <if test="gender != null">
               gender = #{gender},
           </if>
           <if test="email != null">
               email = #{email}
           </if>
       </set>
       <where>
           id = #{id}
       </where>
   </update>

</mapper>
  • 当然,你也可以使用trim标签哦。

7 foreach标签

  • 示例:根据主键批量查询雇员信息

    • SQL语句如下:  
SELECT `id`,`last_name`,`gender`,`email`,`department_id`
FROM `employee`
WHERE id IN (3,4,5);
    • EmployeeMapper.java  
package com.xuweiwei.mybatis.mapper;

import com.xuweiwei.mybatis.pojo.Employee;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface EmployeeMapper {

    public List<Employee> findEmployeesByIds(@Param("ids") Integer[] ids);

}
    • EmployeeMapper.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.xuweiwei.mybatis.mapper.EmployeeMapper">

    <select id="findEmployeesByIds"  resultType="com.xuweiwei.mybatis.pojo.Employee">
        SELECT `id`,`last_name`,`gender`,`email`,`department_id`
        FROM `employee`
        <!--
            foreach标签,遍历集合
            collection:需要遍历的集合
            item:将遍历的每个元素设置到item中
            separator:每个元素之间的分割符
            open:将遍历的结果拼凑一个开始的字符
            close:将遍历的结果拼接一个结束的字符

        -->
        <foreach collection="ids" item="id" open="where id in ( " close=")" separator=",">
            #{id}
        </foreach>
    </select>

</mapper>
    • 测试  
package com.xuweiwei.mybatis.test;

import com.xuweiwei.mybatis.mapper.EmployeeMapper;
import com.xuweiwei.mybatis.pojo.Employee;
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.List;

public class MybatisTest {
    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {

            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            Integer[] ids = new Integer[3];
            ids[0] = 3;
            ids[1] = 4;
            ids[2] = 5;
            List<Employee> employees   = employeeMapper.findEmployeesByIds(ids);
            System.out.println(employees);

        } finally {
            session.close();
        }
    }

}
  • 以MySQL为例,foreach的第二种场景,就是批量插入,示例代码如下

    • EmployeeMapper.java  
package com.xuweiwei.mybatis.mapper;

import com.xuweiwei.mybatis.pojo.Employee;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface EmployeeMapper {

    public boolean insertEmployees(@Param("emps") List<Employee> emps);

}
    • EmployeeMapper.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.xuweiwei.mybatis.mapper.EmployeeMapper">

    <insert id="insertEmployees">
         INSERT INTO `employee` (`last_name`,`gender`,`email`)
         VALUES
         <foreach collection="emps" item="emp" separator=",">
             (#{emp.lastName},#{emp.gender},#{emp.email})
         </foreach>

    </insert>

</mapper>
    • 测试 
package com.xuweiwei.mybatis.test;

import com.xuweiwei.mybatis.mapper.EmployeeMapper;
import com.xuweiwei.mybatis.pojo.Employee;
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 MybatisTest {
    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {

            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            List<Employee> emps = new ArrayList<>();

            Employee emp1 = new Employee();
            emp1.setLastName("aa");
            emp1.setEmail("[email protected]");
            emp1.setGender("男");

            Employee emp2 = new Employee();
            emp2.setLastName("vv");
            emp2.setEmail("[email protected]");
            emp2.setGender("女");

            emps.add(emp1);
            emps.add(emp2);

            System.out.println(employeeMapper.insertEmployees(emps));

            session.commit();

        } finally {
            session.close();
        }
    }

}

8 内置参数

  • Mybatis中不只是方法中传递的参数可以用来判断,取值。
  • Mybatis中默认支持2个内置参数。
  • _parameter:代表整个参数
    • 单个参数,_parameter就是这个参数。
    • 多个参数,会封装到一个map中,_parameter就是这个map。
  • _databaseId:需要配合databaseIDProvider标签使用。  
  • 示例:

    • EmployeeMapper.java  
package com.xuweiwei.mybatis.mapper;

import com.xuweiwei.mybatis.pojo.Employee;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface EmployeeMapper {

    public boolean insertEmployees(@Param("emps") List<Employee> emps);

}
    • EmployeeMapper.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.xuweiwei.mybatis.mapper.EmployeeMapper">

    <insert id="insertEmployees">
        INSERT INTO `employee` (`last_name`,`gender`,`email`)
        VALUES
        <if test="_parameter != null">
            <foreach collection="emps" item="emp" separator=",">
                (#{emp.lastName},#{emp.gender},#{emp.email})
            </foreach>
        </if>
    </insert>

</mapper>

9 bind标签

  • bind元素可以从OGNL表达式中创建一个变量并将其绑定到上下文中。
  • 示例:

    • EmployeeMapper.java  
package com.xuweiwei.mybatis.mapper;

import com.xuweiwei.mybatis.pojo.Employee;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface EmployeeMapper {

    public List<Employee> getEmpByLastName(@Param("lastName") String lastName);

}
    • EmployeeMapper.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.xuweiwei.mybatis.mapper.EmployeeMapper">

    <select id="getEmpByLastName" resultType="com.xuweiwei.mybatis.pojo.Employee">
        <bind name="myLastName" value="‘%‘+lastName+‘%‘"></bind>
        SELECT *
        FROM employee
        where last_name like #{myLastName}

    </select>

</mapper>
    • 测试  
package com.xuweiwei.mybatis.test;

import com.xuweiwei.mybatis.mapper.EmployeeMapper;
import com.xuweiwei.mybatis.pojo.Employee;
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.List;

public class MybatisTest {
    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {

            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            List<Employee> emps = employeeMapper.getEmpByLastName("a");
            System.out.println(emps);
        } finally {
            session.close();
        }
    }

}

10 sql标签

  • sql标签可以将重复的sql抽取出来,以便达到代码重用的目的。
  • 示例:

    • EmployeeMapper.java  
package com.xuweiwei.mybatis.mapper;

import com.xuweiwei.mybatis.pojo.Employee;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface EmployeeMapper {

    public List<Employee> getEmpByLastName(@Param("lastName") String lastName);

}
    • EmployeeMapper.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.xuweiwei.mybatis.mapper.EmployeeMapper">

    <select id="getEmpByLastName" resultType="com.xuweiwei.mybatis.pojo.Employee">
        <bind name="myLastName" value="‘%‘+lastName+‘%‘"></bind>
        SELECT <include refid="selectsql"/>
        FROM employee
        where last_name like #{myLastName}
    </select>
    <sql id="selectsql">
        id,last_name,gender,email
    </sql>

</mapper>
    • 测试  
package com.xuweiwei.mybatis.test;

import com.xuweiwei.mybatis.mapper.EmployeeMapper;
import com.xuweiwei.mybatis.pojo.Employee;
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.List;

public class MybatisTest {
    /**
     * 查询
     *
     * @throws IOException
     */
    @Test
    public void test() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession();
        try {

            EmployeeMapper employeeMapper = session.getMapper(EmployeeMapper.class);
            List<Employee> emps = employeeMapper.getEmpByLastName("a");
            System.out.println(emps);
        } finally {
            session.close();
        }
    }

}

原文地址:https://www.cnblogs.com/xuweiweiwoaini/p/8407204.html

时间: 2024-10-09 19:11:37

Mybatis (三)的相关文章

Mybatis(三) 映射文件详解

前面说了全局配置文件中内容的详解,大家应该清楚了,现在来说说这映射文件,这章就对输入映射.输出映射.动态sql这几个知识点进行说明,其中高级映射(一对一,一对多,多对多映射)在下一章进行说明. 一.输入映射 输入映射:配置statement中输入参数的类型.有四种 1.1.传递简单类型,八大基本类型,比如int类型 findUserById:根据id进行查询对应user,那么传入的就应该是int类型的值.所以使用别名int来映射传入的值 1.2.传递pojo(代表正常的对象,比如user的jav

关于Mybatis三种批量插入方式对比

第一种:普通for循环插入 @Test public void testInsertBatch2() throws Exception { long start = System.currentTimeMillis(); User user; SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(false); UserDao mapper = sqlSession.getMapper(User

浅谈Mybatis(三)

一.动态SQL 1.sql片段 解决sql语句的冗余代码问题. <sql id="SELECT_T_USER"> select id,name,password,birthday </sql> <select id="queryUserById" resultType="User"> <include refid="SELECT_T_USER"/> from t_user whe

spring与mybatis三种整合方法

1.采用MapperScannerConfigurer,它将会查找类路径下的映射器并自动将它们创建成MapperFactoryBean.spring-mybatis.xml: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.

转:spring与mybatis三种整合方法

哎,csdn没转载功能,只能复制了.. 本文主要介绍Spring与Mybatis三种常用整合方法,需要的整合架包是mybatis-spring.jar,可通过链接http://code.google.com/p/mybatis/下载到. 1.采用数据映射器(MapperFactoryBean)的方式,不用写mybatis映射文件,采用注解方式提供相应的sql语句和输入参数.  (1)Spring配置文件: <!-- 引入jdbc配置文件 -->     <context:property

Mybatis三

1.session.commit()为什么会引起事物的提交? 先ctrl+鼠标左键点入commit方法中,然后ctrl+H找到DefaultSqlSession这个类,在这个类中找到如下的方法 然后进入这个方法 这里有一个逻辑关系表达式,运算的顺序是  &&  ||  !的顺序依次运算得到的结果是true,那么该方法的返回值是true 所以执行器的提交,会引起事务的提交 2.session.close()会引起事务的回滚?(同上述方法相似,一步一步往上一层找,就可以找到答案,看到它底层的代

深入浅出Mybatis(三)查询

前言 要对数据库进行操纵,得有一个需求,所以拟定了一个下面的需求,实现下面的功能: 根据用户id查询一个用户信息 根据用户名称模糊查询用户信息列表 添加用户 更新用户 删除用户 程序编写 建立User.java实体类 pojo类作为mybatis进行sql映射使用,pojo类通常与数据库表对应, 在src中建立一个名为cn.itcast.mybatis.pojo的包,在包内建立一个名为User.java的类: package com.dtt.com.dtt.mybatis.pojo; impor

mybatis三种缓存

1.一级缓存 ? MyBatis 默认开启了一级缓存,一级缓存是在SqlSession 层面进行缓存的.即,同一个SqlSession ,多次调用同一个Mapper和同一个方法的同一个参数,只会进行一次数据库查询,然后把数据缓存到缓冲中,以后直接先从缓存中取出数据,不会直接去查数据库. ? 但是不同的SqlSession对象,因为不用的SqlSession都是相互隔离的,所以相同的Mapper.参数和方法,他还是会再次发送到SQL到数据库去执行,返回结果. 2.二级缓存 ? 为了克服这个问题,需

mybatis源码解读(三)——数据源的配置

在mybatis-configuration.xml 文件中,我们进行了如下的配置: <!-- 可以配置多个运行环境,但是每个 SqlSessionFactory 实例只能选择一个运行环境常用: 一.development:开发模式 二.work:工作模式 --> <environments default="development"> <!--id属性必须和上面的default一样 --> <environment id="deve