Mybatis 動態(tài)SQL語句測試筆記

搭建MySQL環(huán)境

CREATE TABLE `blog` (
        `id` VARCHAR(50) NOT NULL COMMENT '博客id',
        `title` VARCHAR(100) NOT NULL COMMENT '博客標(biāo)題',
        `author` VARCHAR(30) NOT NULL COMMENT '博客作者',
        `create_time` datetime NOT NULL COMMENT '博客作者',
        `views` INT(30) NOT NULL COMMENT '瀏覽量'
)ENGINE=INNODB DEFAULT CHARSET=utf8

IDutils工具包

package com.zzqsmile.utils;

import org.junit.Test;

import java.util.UUID;

@SuppressWarnings("all")    //抑制警告
public class IDutils {
    public static String getID(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }

    @Test
    public void test(){
        System.out.println(IDutils.getID());
    }

}

步驟

1.導(dǎo)包

pom.xml

2.編寫配置文件

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"/>
    <!--    可以給實體類起別名-->
    <typeAliases>
        <package name="com.zzqsmile.pojo"/>
<!--        <typeAlias type="com.zzqsmile.pojo.User" alias="User"/>-->
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
<!--                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>-->
<!--                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false"/>-->
<!--                <property name="username" value="root"/>-->
<!--                <property name="password" value="root"/>-->
            </dataSource>
        </environment>

    </environments>

    <!--    綁定接口-->
    <mappers>
        <mapper class="com.zzqsmile.dao.BlogMapper"></mapper>
    </mappers>
</configuration>

db.properties

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=false
username=root
password=root

3.編寫實體類

package com.zzqsmile.pojo;

import lombok.Data;

import java.util.Date;

@Data
public class Blog {
    private String id;
    private String title;
    private String author;
    private Date createTime;
    private int views;

}

4.編寫實體類對應(yīng)的Mapper接口和 Mapper.xml文件

BlogMapper:

package com.zzqsmile.dao;

import com.zzqsmile.pojo.Blog;

import java.util.List;
import java.util.Map;

public interface BlogMapper {
    //插入數(shù)據(jù)
    int addBlog(Blog blog);

    //查詢博客
    List<Blog> queryBlogIF(Map map);

    //選擇查詢
    List<Blog> queryBlogChoose(Map map);

    //更新博客
    int updateBlog(Map map);

   //ForEach
    List<Blog> queryBlogForEach(Map map);
}


BlogMapper.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.zzqsmile.dao.BlogMapper">
    <insert id="addBlog" parameterType="blog">
        insert into mybatis.blog(id,title,author,create_time,views)
        values (#{id},#{title},#{author},#{createTime},#{views})
    </insert>
</mapper>

  • if

BlogMapper.xml

 <mapper>
    <select id="queryBlogIF" parameterType="map" resultType="blog">
        select * from mybatis.blog where 1=1
        <if test="title != null">
            AND title like #{title}
        </if>

        <if test="author != null">
            AND author like #{author}
        </if>

    </select>
 </mapper>

優(yōu)化where

    <select id="queryBlogIF" parameterType="map" resultType="blog">
        select * from mybatis.blog
        <where>
            <if test="title != null">
                AND title like #{title}
            </if>

            <if test="author != null">
                AND author like #{author}
            </if>
        </where>

    </select>

測試:

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

        HashMap map = new HashMap<>();
        map.put("title","Spring");
        map.put("author","zzqsmile");

        List<Blog> blogs = mapper.queryBlogIF(map);

        for (Blog blog : blogs) {
            System.out.println(blog);
        }


        sqlSession.close();
    }
  • choose
    <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>
    </select>
  • updateBlog()
    <update id="updateBlog" parameterType="map">
        update mybatis.blog
        <set>
            <if test="title != null">
                title = #{title},
            </if>

            <if test="author != null">
                author = #{author}
            </if>
        </set>
        where id = #{id}
    </update>
 </mapper>

trim標(biāo)簽可以自定義

  • 動態(tài)SQLForEach
    BlogMapper.xml
<!--    select * from mybatis.blog where 1=1 and (id=1 or id =2 or id=3)-->
    <select id="queryBlogForEach" parameterType="map" resultType="blog">
        select * from mybatis.blog
        <where>
            <foreach collection="ids" item="id" open="and (" close=")" separator="or">
                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<>();
        ids.add(1);
        ids.add(2);
        ids.add(3);
        map.put("ids", ids);


        List<Blog> blogs = mapper.queryBlogForEach(map);

        for (Blog blog : blogs) {
            System.out.println(blog);
        }
        sqlSession.close();
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 1、MyBatis簡介 MyBatis 是一款優(yōu)秀的持久層框架 中文官網(wǎng):https://mybatis.org/...
    CHeng_c0e9閱讀 603評論 0 0
  • 閱讀需要20分鐘 一、MyBatis的開始 從官方文檔[https://mybatis.org/mybatis-3...
    知向誰邊閱讀 316評論 0 0
  • Mybatis-9.28 環(huán)境: JDK1.8 Mysql 5.7 maven 3.6.1 IDEA 回顧: JD...
    眼若繁星丶閱讀 290評論 0 1
  • Mybatis-9.28 環(huán)境: JDK1.8 Mysql 5.7 maven 3.6.1 IDEA 回顧: JD...
    友人Ay閱讀 420評論 0 1
  • 1、簡介 1.1、什么是Mybatis MyBatis 是一款優(yōu)秀的持久層框架 它支持自定義 SQL、存儲過程以及...
    箋札code閱讀 1,574評論 0 0

友情鏈接更多精彩內(nèi)容