第八章 动态SQL

1.动态SQL有什么用?
开发人员在使用JDBC或其他类似的框架进行数据库开发时,通常需要手动拼装SQL,这是一个非常麻烦且痛苦的工作,而MyBatis提供的对SQL语句的组装的功能,恰能解决这一麻烦的工作。
2.动态SQL中的元素:
(1)if:判断语句,用于简单的判断

<!--<if>元素的使用-->
    <select id="findUserByNameAndAddress" parameterType="com.wds.po.User"
        resultType="com.wds.po.User">
        select * from tb_user where 1=1
        <if test="username!=null and username!=''">
            and username like concat('%',#{username},'%')
        </if>
        <if test="address!=null and address!=''">
            and address=#{address}
        </if>


    </select>

(2)choose、when、otherwise:相当于switch…case…default语句,用于多条件判断

<!--<choose>元素的使用-->
    <select id="findUserByNameOrAddress"
            parameterType="com.wds.po.User" resultType="com.wds.po.User">
        select * from tb_user where 1=1
        <choose>
            <when test="username!=null and username!=''">
                and username like concat('%',#{username},'%')
            </when>
            <otherwise>
                and address is not null
            </otherwise>
        </choose>
    </select>

(3)where、trim、set:辅助元素,用于处理一些SQL拼装,特殊字符
注意:
trim的作用是去除特殊的字符串,他的prefix属性代表语句的前缀,prefixOverrides属性代表需要去除的哪些特殊字符串,功能和where是基本等效的

<!--<where>元素的使用-->
    <select id="findUserByNameAndAddress"
            resultType="com.wds.po.User" parameterType="com.wds.po.User">
        select * from tb_user
        <where>
            <if test="username!=null and username!=''">
                and username like concat('%',#{username},'%')
            </if>
            <if test="address!=null and address!=''">
                and address=#{address}
            </if>

        </where>
    </select>
     <!--<trim>元素的使用-->
    <select id="findUserByNameAndAddress" parameterType="com.wds.po.User" resultType="com.wds.po.User">
        select * from tb_user
        <trim prefix="where" prefixOverrides="and">
            <if test="username!=null and username!=''">
                and username like concat('%',#{username},'%')
            </if>
            <if test="address!=null and address!=''">
                and address=#{address}
            </if>
        </trim>
    </select>
     <!--<set>元素的使用-->
    <update id="updateUser" parameterType="com.wds.po.User">
        update tb_user
        <set>
            <if test="username!=null and username!=''">
                username=#{username}
            </if>
            <if test="address!=null and address!=''">
                address=#{address}
            </if>

        </set>
        where id=#{id}
    </update>

(4)foreach:循环语句,常用于in等列举条件中,常用于集合、数组遍历
注意:
item:当前循环中的元素
index:当前元素的下标
collection:list是当前传过来的参数类型(首字母小写),可以是array、list、map的键、pojo包装类中的数组或其他集合的属性名
open和close:以什么符号将这些集合包装起来
separator:个元素的间隔符

    <!--<foreach>元素的使用-->
    <select id="findUserByIds" parameterType="List" resultType="com.wds.po.User">
        select * from tb_user where id in
        <foreach item="id" index="index" collection="list" open="(" separator="," close=")">
            #{id}
        </foreach>
    </select>

注意2:

第八章 动态SQL

(5)bind:从OGNL表达式中创建一个变量,并将其绑定到上下文,常用于模糊查询

 <!--<bind>元素的使用:根据客户名模糊查询客户信息-->
    <select id="findUserByName" parameterType="com.wds.po.User" resultType="com.wds.po.User">
        <bind name="pattern_username" value="'%'+_parameter.getUsername()+'%'"/>
            select * from tb_user where username like #{pattern_username}
    </select>

3.实例演示:
项目结构:
第八章 动态SQL
第八章 动态SQL

db.properties

jdbc.driver = com.mysql.cj.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/mybatis
jdbc.username = root
jdbc.password = 12345678

log4j.properties

# Global logging configuration
log4j.rootLogger=ERROR, stdout
# MyBatis logging configuration...
log4j.logger.com.wds=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties resource="db.properties"/>
    <!--1.配置环境-->
    <environments default="mysql">
        <environment id="mysql">
            <!--只用JDBC的事务管理-->
            <transactionManager type="JDBC"></transactionManager>
            <!--数据库连接池-->
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--2.映射文件-->
    <mappers>
        <mapper resource="com/wds/mapper/UserMapper.xml"/>
    </mappers>
</configuration>

UserMapper.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.wds.mapper.UserMapper">
    <!--<if>元素的使用-->
    <select id="findUserByNameAndAddress" parameterType="com.wds.po.User"
        resultType="com.wds.po.User">
        select * from tb_user where 1=1
        <if test="username!=null and username!=''">
            and username like concat('%',#{username},'%')
        </if>
        <if test="address!=null and address!=''">
            and address=#{address}
        </if>


    </select>
    <!--<choose>元素的使用-->
    <select id="findUserByNameOrAddress"
            parameterType="com.wds.po.User" resultType="com.wds.po.User">
        select * from tb_user where 1=1
        <choose>
            <when test="username!=null and username!=''">
                and username like concat('%',#{username},'%')
            </when>
            <otherwise>
                and address is not null
            </otherwise>
        </choose>
    </select>
    <!--<where>元素的使用-->
    <select id="findUserByNameAndAddress"
            resultType="com.wds.po.User" parameterType="com.wds.po.User">
        select * from tb_user
        <where>
            <if test="username!=null and username!=''">
                and username like concat('%',#{username},'%')
            </if>
            <if test="address!=null and address!=''">
                and address=#{address}
            </if>

        </where>
    </select>
    <!--<trim>元素的使用-->
    <select id="findUserByNameAndAddress" parameterType="com.wds.po.User" resultType="com.wds.po.User">
        select * from tb_user
        <trim prefix="where" prefixOverrides="and">
            <if test="username!=null and username!=''">
                and username like concat('%',#{username},'%')
            </if>
            <if test="address!=null and address!=''">
                and address=#{address}
            </if>
        </trim>
    </select>
    <!--<set>元素的使用-->
    <update id="updateUser" parameterType="com.wds.po.User">
        update tb_user
        <set>
            <if test="username!=null and username!=''">
                username=#{username}
            </if>
            <if test="address!=null and address!=''">
                address=#{address}
            </if>

        </set>
        where id=#{id}
    </update>
    <!--<foreach>元素的使用-->
    <select id="findUserByIds" parameterType="List" resultType="com.wds.po.User">
        select * from tb_user where id in
        <foreach item="id" index="index" collection="list" open="(" separator="," close=")">
            #{id}
        </foreach>
    </select>
    <!--<bind>元素的使用:根据客户名模糊查询客户信息-->
    <select id="findUserByName" parameterType="com.wds.po.User" resultType="com.wds.po.User">
        <bind name="pattern_username" value="'%'+_parameter.getUsername()+'%'"/>
            select * from tb_user where username like #{pattern_username}
    </select>

</mapper>

User.java

package com.wds.po;

public class User {
    private Integer id;
    private String username;
    private String address;

    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 getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

MybatisTest.java

package com.wds.test;

import com.wds.po.User;
import com.wds.utils.Myutils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

public class MybatisTest {
    /**
     * <if></if>元素的使用:根据客户名和地址查询客户信息
     */
    @Test
    public void findUserByNameAndAddress(){
        //通过工具类生成sqlSession对象
        SqlSession sqlSession = Myutils.getSession();
        //创建User对象,封装要查询的组合条件
        User user = new User();
        user.setUsername("科比");
        user.setAddress("洛杉矶");
        //执行sqlSession的查询方法,返回结果
        List<User> users = sqlSession.selectList("com.wds.mapper.UserMapper.findUserByNameAndAddress", user);
        for (User user1:users) {
            System.out.println(user1.toString());

        }
        sqlSession.close();
    }

    /**
     * <choose></choose>元素的使用:根据客户名或地址查询客户信息
     */
    @Test
    public void findUserByNameOrAddress(){
        //通过goon工具类获取sqlSession对象
        SqlSession sqlSession = Myutils.getSession();
        //创建对象,封装要查询的条件
        User user = new User();
        user.setUsername("科比");
        user.setAddress("洛杉矶");
        List<User> users = sqlSession.selectList("com.wds.mapper.UserMapper.findUserByNameOrAddress", user);
        for(User user1:users ){
            System.out.println(user1.toString());
        }
        //关闭sqlSession
        sqlSession.close();

    }
    /**
     * <set></set>元素的使用:更新客户表中的信息
     */
    @Test
    public void updateUser(){
        //获取sqlSession实例
        SqlSession sqlSession = Myutils.getSession();
        //创建User对象,并添加数据
        User user = new User();
        user.setId(2);
        user.setUsername("小王");
        //执行sqlSession的更新方法,返回更新的行数
        int rows = sqlSession.update("com.wds.mapper.UserMapper.updateUser",user);
        if(rows>0){
            System.out.println("您已经成功修改了"+rows+"条数据!!!");
        }else{
            System.out.println("修改未成功!!!");
        }
        //提交事务
        sqlSession.commit();
        //关闭sqlSession
        sqlSession.close();
    }
    /**
     * <foreach></foreach>元素的使用:查询id为1,2的客户信息
     */
    @Test
    public void findUserByIds(){
        //获取sqlSession
        SqlSession sqlSession = Myutils.getSession();
        //创建List集合,封装要查询的id
        List<Integer> ids = new ArrayList<Integer>();
        ids.add(1);
        ids.add(2);
        //执行SqlSession的查询方法,返回结果集
        List<User> users = sqlSession.selectList("com.wds.mapper.UserMapper.findUserByIds", ids);
        //输出查询结果
        for(User user:users){
            System.out.println(user);
        }
        //关闭sqlSession
        sqlSession.close();
    }
    /**
     * <bind></bind>元素的使用:根据客户名模糊查询客户信息
     */
    @Test
    public void findUserByName(){
        SqlSession sqlSession = Myutils.getSession();
        //创建对象,封装查询的条件
        User user = new User();
        user.setUsername("小");
        //执行sqlSession的查询方法,返回结果集
        List<User> users = sqlSession.selectList("com.wds.mapper.UserMapper.findUserByName", user);
        //输出查询结果
        for(User user1:users){
            System.out.println(user1.toString());
        }
        //关闭sqlSession
        sqlSession.close();
    }
}


Myutils.java

package com.wds.utils;

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 java.io.Reader;

public class Myutils {
    //声明静态SqlSessionFactory属性并且赋值为null
    private static SqlSessionFactory sqlSessionFactory=null;
    //静态代码块初始化SqlSessionFactory对象
    static {
        try{
            //使用Mybatis提供的Resources类加载Mybatis的配置文件
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            //构建SqlSessionFactory工厂
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);

        }catch (Exception e)
        {
            e.printStackTrace();
        }
    }
    //获取SqlSession对象的静态方法
    public static SqlSession getSession(){
        return sqlSessionFactory.openSession();
    }

}

运行结果:
if元素的使用:
第八章 动态SQL
choose元素的使用:
第八章 动态SQL

上一篇:MyBatis环境配置与解析


下一篇:2021年上半年最接地气的Java面经,这是一份面向Java开发者的复习指南