码迷,mamicode.com
首页 > 其他好文 > 详细

Mybatis (三)

时间:2018-02-03 00:46:13      阅读:220      评论:0      收藏:0      [点我收藏+]

标签:oid   数据   文本处理   values   other   namespace   data   ike   多个   

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("1975356467@qq.com");
            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("1975356467@qq.com");
            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("1975356467@qq.com");
            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("aa@163.com");
            emp1.setGender("男");



            Employee emp2 = new Employee();
            emp2.setLastName("vv");
            emp2.setEmail("vv@163.com");
            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();
        }
    }


}

 

Mybatis (三)

标签:oid   数据   文本处理   values   other   namespace   data   ike   多个   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!