我们之前写的 SQL 语句都比较简单,如果有比较复杂的业务,我们需要写复杂的 SQL 语句,往往需要拼接,而拼接 SQL ,稍微不注意,由于引号,空格等缺失可能都会导致错误。
那么怎么去解决这个问题呢?这就要使用 mybatis 动态SQL,通过 if, choose, when, otherwise, trim, where, set, foreach等标签,可组合成非常灵活的SQL语句,从而在提高 SQL 语句的准确性的同时,也大大提高了开发人员的效率。
通过动态标签,来实现动态链接,SQL在开发中大量使用,所以一定要熟练掌握
1.if标签 :满足条件时,if标签才会链接
2.where标签:它包含标签中有返回值的话,它就会插入一个where,如果标签返回内容是以AND或OR开头的话,则它会剔除掉
3.set标签:在至少有一个子元素返回了SQL语句时,才会向SQL语句中添加SET,并且如果SET之后是以,开头的话,会自动将其删掉
4.choose标签:有时候用不到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用choose标签可以满足
5.SQL片段:有时候可以通过将部分代码抽出来作为公用,使用时候可以直接调用
6.Foreach:对集合进行遍历
1.前提工作
需知:不太熟悉的小伙伴可以查看以往博客内容
2.构建并搭建完毕项目
1.在数据库中创建一个blog表单
CREATE TABLE `blog` ( `id` varchar(50) NOT NULL COMMENT '博客id', `title` varchar(100) NOT NULL COMMENT '博客标题', `author` varchar(30) NOT NULL COMMENT '博客作者', `create_time` datetime NOT NULL COMMENT '创建时间', `views` int(30) NOT NULL COMMENT '浏览量' ) ENGINE=InnoDB DEFAULT CHARSET=utf8
2.idea创建一个maven项目:
3.配置pom依赖和mybatis核心配置
pom中依赖导入
<packaging>jar</packaging> <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.11</version> <scope>test</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.12</version> </dependency> <dependency> <groupId>org.example</groupId> <artifactId>mybatis_test5</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13.2</version> <scope>test</scope> </dependency> </dependencies>
mybatis.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> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> <setting name="logImpl" value="STDOUT_LOGGING"/> </settings> <environments default="mysql"> <environment id = "mysql"> <transactionManager type="JDBC"></transactionManager> <dataSource type = "POOLED"> <property name="driver" value="com.mysql.jdbc.Driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/bobo?useSSL=false&useUnicode=true&characterEncoding=utf8"></property> <property name="username" value="root"></property> <property name="password" value="123456"></property> </dataSource> </environment> </environments> <mappers> <mapper resource="cn/bobo/BolgMapper/BolgMapper.xml"/> </mappers> </configuration>
4.创建实体类和接口
实体类:自己实现get set方法:
package cn.bobo.BolgDao; import java.util.Date; public class Bolg { private String id; private String title; private String author; private Date createTime; private int views }
接口:
public interface BolgMapper { int addBolg(Bolg bolg);
5.实现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="cn.bobo.BolgMapper.BolgMapper"> <insert id="addBolg" parameterType="cn.bobo.BolgDao.Bolg"> insert into blog (id, title, author, create_time, views) values (#{id},#{title},#{author},#{createTime},#{views}); </insert> </mapper>
6.创建测试类,进行测试
package cn.bobo; import cn.bobo.BolgDao.Bolg; import cn.bobo.BolgMapper.BolgMapper; import cn.bobo.Tools.IDutil; 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.After; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.HashMap; import java.util.List; public class test { public InputStream in; public SqlSession sqlSession; public BolgMapper bolgMapper; public SqlSessionFactory factory; @Before public void init() throws IOException { //读取配置文件,生成字节输入流 in = Resources.getResourceAsStream("mybatis.xml"); //获取sqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); //获取sqlSession对象 sqlSession = factory.openSession(); //获取dao的代理对象 bolgMapper = sqlSession.getMapper(BolgMapper.class); } @After public void destroy() throws IOException { //提交事务 sqlSession.commit(); sqlSession.close(); in.close(); } @Test public void addInitBlog(){ Bolg bolg = new Bolg(); bolg.setId(IDutil.genld()); bolg.setTitle("wuhu"); bolg.setAuthor("xiaobo"); bolg.setCreateTime(new Date()); bolg.setViews(9999); bolgMapper.addBolg(bolg); bolg.setId(IDutil.genld()); bolg.setTitle("Java如此简单"); bolgMapper.addBolg(bolg); bolg.setId(IDutil.genld()); bolg.setTitle("Spring如此简单"); bolgMapper.addBolg(bolg); bolg.setId(IDutil.genld()); bolg.setTitle("hahha"); bolgMapper.addBolg(bolg); } @Test public void testQueryBolgif(){ HashMap<String,String> map = new HashMap<String, String>(); map.put("title","wuhu"); map.put("author","xiaobo"); List<Bolg> bolgs = bolgMapper.queryBolgIf(map); System.out.println(bolgs); } @Test public void testUpdateBolg(){ HashMap<String,String> } }
3.if标签
编写接口:
List queryBlogIf(Map map);
编写SQL语句:
<select id="queryBlogIf" parameterType="map" resultType="blog"> select * from blog where <if test="title != null"> title = #{title} </if> <if test="author != null"> and author = #{author} </if> </select>
测试:
@Test public void testQueryBlogIf(){ SqlSession session = MybatisUtils.getSession(); BlogMapper mapper = session.getMapper(BlogMapper.class); HashMap<String, String> map = new HashMap<String, String>(); map.put("title","Mybatis如此简单"); map.put("author","狂神说"); List<Blog> blogs = mapper.queryBlogIf(map); System.out.println(blogs); session.close(); }
结果:
这里能看到如果title为空 则会执行第二个if语句,开头是and 所以会显示报错,所以我们用到where标签