版权声明:原创文章,相互提高。 https://blog.csdn.net/xu1916659422/article/details/78110868
点滴记载,点滴进步,愿自己更上一层楼。
choose节点,用法跟java中的switch 语法相似(官方文档这么说,事实也是这样)。
节点用法。
<choose>
<when test="username != null">
username = #{username}
</when>
<when test="password != null">
password = #{password}
</when>
<otherwise>
1=1
</otherwise>
</choose>
里面的一条条的when其实就相当于一条条的 <if test ....
mybatis在解析choose节点的时候就是将一条条的when放入到list中,otherwise 相关内容专门放到一个对象中,
然后循环着查找条件成立的一条,然后将该条的sql拼接到sql中,如果when条件都不成立,则直接执行otherwise中的内容。
源码:
public class ChooseSqlNode implements SqlNode {
private SqlNode defaultSqlNode;
private List<SqlNode> ifSqlNodes;
public ChooseSqlNode(List<SqlNode> ifSqlNodes, SqlNode defaultSqlNode) {
this.ifSqlNodes = ifSqlNodes;
this.defaultSqlNode = defaultSqlNode;
}
@Override
public boolean apply(DynamicContext context) {
for (SqlNode sqlNode : ifSqlNodes) {
if (sqlNode.apply(context)) {
return true;
}
}
if (defaultSqlNode != null) {
defaultSqlNode.apply(context);
return true;
}
return false;
}
}
简单明了。