Mybatis 动态SQL
Mybatis 动态SQL OGNL表达式
在 MyBatis 中提供了动态 SQL 功能。将使用 Java 代码拼接 SQL 语句,改变为在 XML 映65
射文件中使用标签拼接 SQL 语句。 MyBatis 中动态 SQL 是编写在 mapper.xml 中的,其语法和 JSTL 类似,但是却是基于强大 的 OGNL 表达式实现的。
1.添加多条件查询 用if
1.1在mapper配置文件中修改sql,添加多条件查询
代码片段
点击查看代码
点击查看代码
package com.bjsxt.service.impl;
import com.bjsxt.mapper.UsersMapper;
import com.bjsxt.pojo.Users;
import com.bjsxt.service.UsersService;
import com.bjsxt.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import java.util.List;
public class UsersServiceImpl implements UsersService {
@Override
public List selectUsersByProperty(Users users) {
SqlSession sqlSession = MybatisUtil.getSqlSession();
UsersMapper usersMapper = sqlSession.getMapper(UsersMapper.class);
List list = usersMapper.selectUsersByProperty(users);
return list;
}
}
2.choose when otherwise
用法和switch差不多,进行多选一查询时,可用
代码片段
点击查看代码
3.where
使用 where 标签,就不需要提供 where 1=1 这样的条件了。如果判断条件不为空则自 动添加 where 关键字,并且会自动去掉第一个条件前面的 and 或 or。
代码片段
点击查看代码
4.bind
bind 标签允许我们在 OGNL 表达式以外创建一个变量,并可以将其绑定到当前的 SQL 语句中。一般应用于模糊查询,通过 bind 绑定通配符和查询值。
代码片段‘
点击查看代码
5.set
set 标签用在 update 语句中。借助 if 标签,可以只对有具体值的字段进行更新。set 标 签会自动添加 set 关键字,自动去掉最后一个 if 语句的多余的逗号。
点击查看代码
update users
username = #{username},
usersex = #{usersex},
where userid = #{userid}
6.foreach
foreach 标签的功能非常强大,我们可以将任何可迭代对象如 List、Set 、Map 或者数 组对象作为集合参数传递给 foreach 标签进行遍历。它也允许我们指定开头与结尾的字符串 以及集合项迭代之间的分隔符。
点击查看代码
6.1
数组(array)存放
点击查看代码
6.2
map存放
注意${} 和 #{} 获取值的区别
点击查看代码
6.3
同时添加多个值
点击查看代码
insert into users value
(default,#{user.username},#{user.usersex} )