动态SQL

官方文档


动态SQL就是指根据不同的条件生成不同的SQL语句

搭建环境

创建数据库:

CREATE TABLE blog(
id VARCHAR(50) NOT NULL COMMENT '博客id',
title VARCHAR(100) not null comment '博客标题',
author VARCHAR(30) not null comment '博客作者',
creat_time datetime not null comment '创建时间',
views int(30) not null comment '浏览量'
)ENGINE=InnoDB DEFAULT CHARSET=utf8

实体类:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Blog {
    private String id;
    private String title;
    private String author;
    private Date createTime; //与数据库字段不一致
    private int views;
}

工具类:

public class MybatisUtils {

    private static SqlSessionFactory sqlSessionFactory;

    //使用mybatis的第一步,获取sqlSessionFactory对象
    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //既然有了 SqlSessionFactory,我们可以从中获得 SqlSession 的实例。
    // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession(true);
    }

}
public class IdUtils {
    public static String getId(){
        return UUID.randomUUID().toString().replace("-","");
    }

    @Test
    public void test(){
        System.out.println(IdUtils.getId());
    }
}

接口:

public interface BlogMapper {

    List<Blog> queryBlog(Map map);
}

if的使用

if:根据条件包含 where 子句的一部分

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.BlogMapper">
    <insert id="addBlog" parameterType="pojo.Blog">
        insert into blog values(#{id},#{title},#{author},#{createTime},#{views})
    </insert>
    

    <select id="queryBlog" parameterType="map" resultType="pojo.Blog">
        select * from blog where 1=1
        <if test="author != null">
            and author = #{author}
        </if>
        <if test="views != null">
            and views > #{views}
        </if>
    </select>


</mapper>

测试:

    @org.junit.Test
    public void testQueryBlog(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);


        HashMap map = new HashMap();
       // map.put("author","chz");
        map.put("views",300);

        List<Blog> blogs = mapper.queryBlog(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
    }

where的使用

上述sql语句select * from blog where 1=1为了拼接sql语句使用了where 1=1,显示它不符合正常的sql语句使用,由此使用where标签。

where标签:where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

    <select id="queryBlog" parameterType="map" resultType="pojo.Blog">
        select * from blog
        <where>
            <if test="author != null">
                and author = #{author}
            </if>
            <if test="views != null">
                and views > #{views}
            </if>
        </where>

    </select>

choose、when、otherwise

choose 元素,类似于 Java 中的 switch 语句

    <select id="queryBlogChoose" parameterType="map" resultType="Blog">
        select * from mybatis.blog
        <where>
            <choose>
                <when test="title !=null">
                    title=#{title}
                </when>
                <when test="author !=null">
                   and author=#{author}
                </when>
                <otherwise>
                    and views=#{views}
                </otherwise>
            </choose>
        </where>

foreach

对集合进行遍历(尤其是在构建 IN 条件语句的时候)


    <select id="queryBlogForeach" parameterType="map" resultType="Blog">
        select * from mybatis.blog
        <where>
            <foreach collection="ids" item="id" open="and (" separator="or" close=")" >
                id=#{id}
            </foreach>
        </where>
    </select>

测试:


    @Test
    public void queryBlogForeach(){
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        ArrayList<Integer> ids = new ArrayList<Integer>();
        ids.add(1);
        ids.add(2);
 
        map.put("ids",ids);
 
        List<Blog> blogs = mapper.queryBlogForeach(map);
 
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
 
        sqlSession.close();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值