动态SQL的应用场景
在JDBC
或者其他框架中的拼接SQL
的场景。
Mybatis动态SQL包含的元素
元素 | 作用 | 备注 |
---|---|---|
if |
判断语句 | 单条件分支判断 |
choose(when、otherwise) |
相当于 Java 中的 switch case 语句 | 多条件分支判断 |
trim 、where |
辅助元素 | 用于处理一些SQL拼装问题 |
foreach |
循环语句 | 在in语句等列举条件常用 |
bind |
辅助元素 | 拼接参数 |
if标签
判断条件,常与test
属性连用:
语法:
<if test="判断条件">
SQL语句
</if>
判断条件为true
则会执行语句。
可以多个判断,可以单个判断,可以和where
子句一起使用。
上诉语句的意义:
-
可以按照网站名称(name)或者网址(url)进行模糊查询
-
如果不传参则返回全部的网站信息
choose...when...otherwise标签
选择执行条件,类似Java
当中的switch...case...default
语句
Mybatis框架中没有if...else
标签
语法:
<choose>
<when test="判断条件1">
SQL语句1
</when>
<when test="判断条件2">
SQL语句2
</when>
<when test="判断条件3">
SQL语句3
</when>
<otherwise>
SQL语句4
</otherwise>
</choose>
说明:
-
when
标签中的判断条件是否成立,如果有一个成立,则执行相应的SQL
语句,choose
执行结束 -
如果when 标签中的判断条件都不成立,执行
otherwise
中的SQL
语句
示例代码:
需求:
-
当网站名称不为空时,只用网站名称作为条件进行模糊查询;
-
当网站名称为空,而网址不为空时,则用网址作为条件进行模糊查询;
-
当网站名称和网址都为空时,则要求网站年龄不为空。
websiteMapper.xml
:
websiteMapper
接口类:
package com.junkingboy.mapper;
import com.junkingboy.bean.Student;
import com.junkingboy.bean.User;
import com.junkingboy.bean.Website;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.type.JdbcType;
import java.util.List;
import java.util.Map;
/**
* @description:mybatis框架测试接口,该接口定义了.xml文件操作的表用到的方法
* @data: 2021/11/2 16:35
* @author: Lucifer
*/
public interface WebsiteMapper {
/* 查询所有网站信息,传参为Website对象 */
List<Website> selectWebsite(Website website);
}
测试类:
package com.junkingboy.mapper;
import com.junkingboy.bean.Website;
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.InputStream;
import java.util.List;
import java.util.Map;
/**
* @description:WebsiteMapper接口的实现类,实现了WebsiteMapper接口
* @data: 2021/11/5 17:18
* @author: Lucifer
*/
public class WebsiteMapperImpl<T> implements WebsiteMapper {
//创建表的实现类对象
Website website = new Website();
List<Website> websiteList;
InputStream is = null;
SqlSessionFactory ssf;
SqlSession ss;
Boolean openSwitch = null;
Integer changeNum = 0;
/*
步骤:
Io流读取配置文件
使用SqlSessionFactory接口实现类加载配置文件
使用SqlSession接口开启连接
获取WebsiteMapper接口定义的方法
执行接口当中的方法
*/
/*获取读取配置文件的方法*/
private Boolean readProperties() {
try {
is = Resources.getResourceAsStream("xml/mybatis-config.xml");
}catch (Exception e) {
/*结束方法*/
System.out.println("找不到配置文件!");
e.printStackTrace();
return false;
}
return true;
}