MyBatis 的强大特性之一便是它的动态 SQL。如果你有使用 JDBC 或其他类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句有多么痛苦。拼接的时候要确保不能忘了必要的空格,还要注意省掉列名列表最后的逗号。利用动态 SQL 这一特性可以彻底摆脱这种痛苦。它借助ognl(类似于jsp里面的el表达式)表达式来完成动态sql的拼接使得非常简便。
实习 动态 SQL 的方式
-
if条件判断
-
choose, when, otherwise 选择器使用
-
trim, where, set
-
foreach
-
使用Ognl表达式
案例实操
if条件判断
动态 SQL 通常要做的事情是有条件地包含 where 子句的一部分。比如:
<!-- 模糊匹配 -->
<select id="queryUserByUserName" parameterType="string" resultType="user">
select id,userName,userPwd from user where 1=1
<if test="userName!=null and userName!=''">
and userName like '%#{userName}%'
</if>
</select>
使用if标签就是加一个test属性作为判断, 如果有多个条件组合判断的话用and, or连接
实现方法
@Override
public List<User> queryUserByUserName(String userName) {
List<User> users=null;
SqlSession session=null;
try {
session=sqlSessionFactory.openSession();
Map map=new HashMap();
//map 参数
map.put("userName",userName);
users=session.selectList("com.xxx.mapper.UserMapper.queryUserByUserName", map);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(null!=session){
session.close();
}
}
return users;
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VX4hL0VP-1602571506221)(https://imgkr2.cn-bj.ufileos.com/6c5fe387-492c-4721-89aa-c8560f6a528f.png?UCloudPublicKey=TOKEN_8d8b72be-579a-4e83-bfd0-5f6ce1546f13&Signature=bC8cFRwCZAEavYH%252FBpq18iDwJ1Y%253D&Expires=1596378864)]
运行结果, sql自动判断并且拼接上了
choose, when, otherwise 选择器使用
我们不想用到所有的条件语句,而只想从中择其一二。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句
<select id="queryUserByParams" parameterType="map" resultType="user">
select id,userPwd
<choose>
<when test="nation!=null and nation!=''">
,userName
</when>
<otherwise>
,realName
</otherwise>
</choose>
from user
where userName like '%${userName}%'
<if test="phone!=null and phone!=''">
and phone like '%${phone}%'
</if>
</select>
这条语句的意思就是说 如果我传进nation不为空就查userName的值, 否则是realName的值
@Test
public void test16(){
UserDao userDao=new UserDaoImpl(sqlSessionFactory);
List<User> list=userDao.queryUserByParams("", null, "xxx");
for(User u:list){
System.out.println(u);
}
}
trim, where, set
前面几个例子已经适宜地解决了一个臭名昭著的动态 SQL 问题, 然后我们再来看第一条的配置
<select id="findUserByUserName" resultMap="RM_User" >
select
userId, userName, password
from
user
where
userName like '%${userName}%'
<if test="phone != null and phone != ''" >
and phone like '%${phone}%'
</if>
</select>
如果我把 userName like '%${userName}%'这个语句也用if做个判断
<select id="findUserByUserName" resultMap="RM_User" >
select
userId, userName, password
from
user
where
<if test="userName != null and userName != ''" >
userName like '%${userName}%'
</if>
<if test="phone != null and phone != ''" >
and phone like '%${phone}%' 需要视频配套资料或其他资料+我们小姐姐V lezi