日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 运维知识 > 数据库 >内容正文

数据库

MyBatis(三)——动态SQL

發(fā)布時(shí)間:2025/3/13 数据库 16 豆豆
生活随笔 收集整理的這篇文章主要介紹了 MyBatis(三)——动态SQL 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

文章目錄

  • 1. 簡(jiǎn)介
  • 2. 搭建環(huán)境
    • 2.1 在MySQL中創(chuàng)建blog表
    • 2.2 編寫實(shí)體類
    • 2.3 編寫實(shí)體類對(duì)應(yīng)Mapper接口
    • 2.4 編寫Mapper接口對(duì)應(yīng)的Mapper.xml文件
    • 2.5 編寫測(cè)試類
  • 3. if
  • 4. where
  • 5. set
  • 6. choose
  • 7. foreach

1. 簡(jiǎn)介

動(dòng)態(tài)SQL就是指根據(jù)不同的條件生成不同的SQL語(yǔ)句

傳統(tǒng)的使用JDBC的方法,在組合復(fù)雜的的SQL語(yǔ)句的時(shí)候,需要去拼接,稍不注意哪怕少了個(gè)空格,都會(huì)導(dǎo)致錯(cuò)誤。Mybatis的動(dòng)態(tài)SQL功能正是為了解決這種問題, 其通過 if, choose, when, otherwise, trim, where, set, foreach標(biāo)簽,可組合成非常靈活的SQL語(yǔ)句,從而提高開發(fā)人員的效率。

2. 搭建環(huán)境

2.1 在MySQL中創(chuàng)建blog表

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 '創(chuàng)建時(shí)間',`views` int(30) NOT NULL COMMENT '瀏覽量' ) ENGINE=InnoDB DEFAULT CHARSET=utf8

2.2 編寫實(shí)體類

package com.zz.pojo;import lombok.Data;import java.util.Date;@Data public class Blog {private String id;private String title;private String author;private Date createDate;private int views;}

可選擇在idea中連接數(shù)據(jù)庫(kù)

解決辦法:在mybatis-config.xml中開啟駝峰命名
同時(shí)也開啟日志

<!--開啟日志和駝峰命名--><settings><setting name="mapUnderscoreToCamelCase" value="true"/><setting name="logImpl" value="STDOUT_LOGGING"/></settings>

2.3 編寫實(shí)體類對(duì)應(yīng)Mapper接口

package com.zz.mapper;import com.zz.pojo.Blog;public interface BlogMapper {//新增一個(gè)博客int addBlog(Blog blog); }

2.4 編寫Mapper接口對(duì)應(yīng)的Mapper.xml文件

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.zz.mapper.BlogMapper"><insert id="addBlog" parameterType="Blog">insert into mybatis.blog (id, title, author, create_time, views)values (#{id},#{title},#{author},#{createDate},#{views}); </insert></mapper>

2.5 編寫測(cè)試類

可選擇在util目錄下創(chuàng)建IDUtils工具類,因?yàn)樵谡鎸?shí)開發(fā)中id一般是隨機(jī)的數(shù)字,調(diào)用IDUtils類,保證生成的id都不相同。

package com.zz.utils;import java.util.UUID;public class IDUtils {public static String getId(){return UUID.randomUUID().toString().replaceAll("-","");} }

編寫測(cè)試類,往數(shù)據(jù)庫(kù)中添加八篇博客

package com.zz.mapper;import com.zz.pojo.Blog; import com.zz.utils.IDUtils; import com.zz.utils.MyBatisUtils; import org.apache.ibatis.session.SqlSession; import org.junit.Test;import java.util.Date;public class BlogMapperTest {@Testpublic void testAddBlog(){SqlSession session = MyBatisUtils.getSession();BlogMapper mapper = session.getMapper(BlogMapper.class);Blog blog01 = new Blog();//調(diào)用IDUtils包,保證id都不相同blog01.setId(IDUtils.getId()); //真實(shí)開發(fā)中id一般是隨機(jī)的數(shù)字(uuid)blog01.setTitle("Hello MyBatis");blog01.setAuthor("大佬");blog01.setCreateDate(new Date());blog01.setViews(9999);mapper.addBlog(blog01);Blog blog02 = new Blog();//調(diào)用IDUtils包,保證id都不相同blog02.setId(IDUtils.getId()); //真實(shí)開發(fā)中id一般是隨機(jī)的數(shù)字(uuid)blog02.setTitle("Hello JDBC");blog02.setAuthor("大佬");blog02.setCreateDate(new Date());blog02.setViews(9999);mapper.addBlog(blog02);Blog blog03 = new Blog();//調(diào)用IDUtils包,保證id都不相同blog03.setId(IDUtils.getId()); //真實(shí)開發(fā)中id一般是隨機(jī)的數(shù)字(uuid)blog03.setTitle("Hello MySQL");blog03.setAuthor("大佬");blog03.setCreateDate(new Date());blog03.setViews(9999);mapper.addBlog(blog03);Blog blog04 = new Blog();//調(diào)用IDUtils類,保證id都不相同blog04.setId(IDUtils.getId()); //真實(shí)開發(fā)中id一般是隨機(jī)的數(shù)字(uuid)blog04.setTitle("Hello Spring");blog04.setAuthor("大佬");blog04.setCreateDate(new Date());blog04.setViews(9999);mapper.addBlog(blog04);session.commit(); //提交事務(wù)} }

運(yùn)行結(jié)果:

至此,環(huán)境搭建完畢!

3. if

接口BlogMapper的代碼:

package com.zz.mapper;import com.zz.pojo.Blog;import java.util.List; import java.util.Map;public interface BlogMapper {//新增一個(gè)博客int addBlog(Blog blog);//通過作者名和博客名來查詢博客//如果作者名為空,則根據(jù)博客名來查詢List<Blog> getBlogByIf(Map map); }

接口的配置文件BlogMapper.xml 代碼:

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.zz.mapper.BlogMapper"><insert id="addBlog" parameterType="Blog">insert into mybatis.blog (id, title, author, create_time, views)values (#{id},#{title},#{author},#{createDate},#{views}); </insert><select id="getBlogByIf" resultType="Blog" parameterType="map">select * from mybatis.blog where<if test="title!=null">title=#{title}</if><if test="author!=null">and author=#{author}</if></select></mapper>

測(cè)試類BlogMapperTest 代碼:

  • 當(dāng)在map中只添加title時(shí)
public class BlogMapperTest {//測(cè)試if@Testpublic void testGetBlogByIf(){SqlSession session = MyBatisUtils.getSession();BlogMapper mapper = session.getMapper(BlogMapper.class);Map<String, String> map = new HashMap<String, String>();map.put("title","Hello MyBatis");//map.put("author","小白");List<Blog> blogByIf = mapper.getBlogByIf(map);for (Blog blog : blogByIf) {System.out.println(blog);}} }

運(yùn)行結(jié)果:

  • 當(dāng)在map中添加title和author時(shí)
public class BlogMapperTest {//測(cè)試if@Testpublic void testGetBlogByIf(){SqlSession session = MyBatisUtils.getSession();BlogMapper mapper = session.getMapper(BlogMapper.class);Map<String, String> map = new HashMap<String, String>();map.put("title","Hello MyBatis");map.put("author","小白");List<Blog> blogByIf = mapper.getBlogByIf(map);for (Blog blog : blogByIf) {System.out.println(blog);}} }

運(yùn)行結(jié)果:

可以看出:根據(jù)不同的條件生成不同的SQL語(yǔ)句,即動(dòng)態(tài)SQL

4. where

使用場(chǎng)景:如果我們需要拼接where條件,又不希望客戶端傳遞錯(cuò)誤信息,這時(shí)需要使用where 標(biāo)簽。
作用:如果后面有語(yǔ)句,就自動(dòng)添加where;如果后面語(yǔ)句開頭是and 或者or,它可以自動(dòng)去掉。

接口的配置文件BlogMapper.xml 代碼:
注意:在author 前添加了 and

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.zz.mapper.BlogMapper"><insert id="addBlog" parameterType="Blog">insert into mybatis.blog (id, title, author, create_time, views)values (#{id},#{title},#{author},#{createDate},#{views}); </insert><select id="getBlogByIf" resultType="Blog" parameterType="map">select * from mybatis.blog<where><if test="title!=null">title=#{title}</if><if test="author!=null">and author=#{author}</if></where></select></mapper>

測(cè)試類BlogMapperTest 的代碼:

  • 當(dāng)在map中什么都不添加,為空時(shí)
public class BlogMapperTest {//測(cè)試where@Testpublic void testGetBlogByIf(){SqlSession session = MyBatisUtils.getSession();BlogMapper mapper = session.getMapper(BlogMapper.class);Map<String, String> map = new HashMap<String, String>();//map.put("title","Hello MyBatis");//map.put("author","小白");List<Blog> blogByIf = mapper.getBlogByIf(map);for (Blog blog : blogByIf) {System.out.println(blog);}} }

運(yùn)行結(jié)果:

可以看出:查詢出了所有的博客

  • 當(dāng)在map中只添加author時(shí)
public class BlogMapperTest { //測(cè)試where@Testpublic void testGetBlogByIf(){SqlSession session = MyBatisUtils.getSession();BlogMapper mapper = session.getMapper(BlogMapper.class);Map<String, String> map = new HashMap<String, String>();//map.put("title","Hello MyBatis");map.put("author","小白");List<Blog> blogByIf = mapper.getBlogByIf(map);for (Blog blog : blogByIf) {System.out.println(blog);}} }

運(yùn)行結(jié)果:

可以看出,把配置文件中的 and 去掉了

5. set

如果里面的條件滿足,自動(dòng)拼接set標(biāo)簽;后面如果有多余的逗號(hào),可以自動(dòng)去除

接口BlogMapper的代碼:

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

接口的配置文件BlogMapper.xml 代碼:

注意:在title 后添加了逗號(hào)

<insert 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}</insert>

測(cè)試類BlogMapperTest 的代碼:

map中必須添加id,否則會(huì)報(bào)錯(cuò)

  • 當(dāng)在map中只添加id和author時(shí)
//測(cè)試set@Testpublic void testSet(){SqlSession session = MyBatisUtils.getSession();BlogMapper mapper = session.getMapper(BlogMapper.class);HashMap<String, String> map = new HashMap<String, String>();map.put("id","74205db5524c4e92942241e8b6443032");map.put("author","大佬");//map.put("title","大佬");mapper.updateBlog(map);session.commit();}

運(yùn)行結(jié)果:

  • 當(dāng)在map中添加id,author和title時(shí)
//測(cè)試set@Testpublic void testSet(){SqlSession session = MyBatisUtils.getSession();BlogMapper mapper = session.getMapper(BlogMapper.class);HashMap<String, String> map = new HashMap<String, String>();map.put("id","74205db5524c4e92942241e8b6443032");map.put("author","大佬");map.put("title","大佬");mapper.updateBlog(map);session.commit();}

運(yùn)行結(jié)果:

  • 當(dāng)在map中只添加id和title時(shí)
//測(cè)試set@Testpublic void testSet(){SqlSession session = MyBatisUtils.getSession();BlogMapper mapper = session.getMapper(BlogMapper.class);HashMap<String, String> map = new HashMap<String, String>();map.put("id","74205db5524c4e92942241e8b6443032");//map.put("author","大佬");map.put("title","大佬");mapper.updateBlog(map);session.commit();}

運(yùn)行結(jié)果:

可以發(fā)現(xiàn):title 后面的逗號(hào)去掉了

where標(biāo)簽和set 標(biāo)簽的底層都是trim標(biāo)簽

6. choose

好比java中的switch

接口BlogMapper的代碼:

//查詢博客 但是只要有一個(gè)條件滿足即可 List<Blog> queryBlogByChoose(Map map);

接口的配置文件BlogMapper.xml 代碼:

<select id="queryBlogByChoose" 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>

測(cè)試類BlogMapperTest 的代碼:

  • 當(dāng)在map中什么都不添加時(shí)
//測(cè)試choose@Testpublic void testChoose(){SqlSession session = MyBatisUtils.getSession();BlogMapper mapper = session.getMapper(BlogMapper.class);HashMap<String, String> map = new HashMap<String, String>();mapper.queryBlogByChoose(map);session.commit();}

運(yùn)行結(jié)果:

  • 當(dāng)在map中只添加title時(shí)
//測(cè)試choose@Testpublic void testChoose(){SqlSession session = MyBatisUtils.getSession();BlogMapper mapper = session.getMapper(BlogMapper.class);HashMap<String, String> map = new HashMap<String, String>();map.put("title","Hello Spring");mapper.queryBlogByChoose(map);session.commit();}

運(yùn)行結(jié)果:

  • 當(dāng)在map中只添加author時(shí)
//測(cè)試choose@Testpublic void testChoose(){SqlSession session = MyBatisUtils.getSession();BlogMapper mapper = session.getMapper(BlogMapper.class);HashMap<String, String> map = new HashMap<String, String>();//map.put("title","Hello Spring");map.put("author","大佬");mapper.queryBlogByChoose(map);session.commit();}

運(yùn)行結(jié)果:

  • 當(dāng)在map中添加title和author時(shí)
//測(cè)試choose@Testpublic void testChoose(){SqlSession session = MyBatisUtils.getSession();BlogMapper mapper = session.getMapper(BlogMapper.class);HashMap<String, String> map = new HashMap<String, String>();map.put("title","Hello Spring");map.put("author","大佬");mapper.queryBlogByChoose(map);session.commit();}

運(yùn)行結(jié)果:

可以看出:雖然傳入了兩個(gè)參數(shù),但只顯示了一個(gè)

7. foreach

相當(dāng)于子查詢 where in(1,2,3)

collection 表示輸入的參數(shù) map
item 表示遍歷出來的每一項(xiàng)
open 表示打開
close 表示關(guān)閉
separator 表示分割符
通過item 遍歷出來的標(biāo)簽可以在foreach中使用

接口BlogMapper的代碼:

List<Blog> queryBlogByForeach(Map map);

接口的配置文件BlogMapper.xml 代碼:

<!--子查詢 where in(1,2,3)--><select id="queryBlogByForeach" parameterType="map" resultType="Blog">select * from mybatis.blog<where><foreach collection="ids" item="id" open="and (" close=")" separator="or">id = #{id}</foreach></where></select>

測(cè)試類BlogMapperTest 代碼:

//測(cè)試foreach@Testpublic void testForeach(){SqlSession session = MyBatisUtils.getSession();BlogMapper mapper = session.getMapper(BlogMapper.class);Map<String,List> map = new HashMap();List<String> ids = new ArrayList<String>();ids.add("bac368d88b4a4d8eb6bd1b539a3338a0");ids.add("321c98e9beea45d092c39b2cfe0fc370");ids.add("cfbc34f0a1dd40fdba91e99dfe4c365a");map.put("ids",ids);mapper.queryBlogByForeach(map);session.commit();}

運(yùn)行結(jié)果:

可以看出:就相當(dāng)于SQL中的 select * from mybatis.blog where and (id=xxx or id=xxx or id=xxx)

總結(jié)

以上是生活随笔為你收集整理的MyBatis(三)——动态SQL的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。