Skip to content

7.动态sql

FuriousPws002 edited this page Apr 17, 2024 · 1 revision

代码分支:07-dynamic-sql

本章节支持如下三种标签的动态SQL解析

  1. if
  2. trim
  3. foreach

标签对应的处理器如下

Tag SqlNode NodeHandler
if IfSqlNode IfHandler
trim TrimSqlNode TrimHandler
foreach ForeachSqlNode ForeachHandler

DynamicSqlSource类用于生成动态SQL的BoundSql,XMLScriptBuilder的parseDynamicTags方法用递归的方式处理xml中的标签树信息

单元测试:

public class SqlSessionTest {
    /**
     * 动态SQL-包含trim标签和if标签
     */
    @Test
    public void queryDynamicSql() {
        UserMapper userMapper = getUserMapper();
        List<UserDO> list1 = userMapper.listDynamic(null, null);
        Assert.assertNotNull(list1);
        List<UserDO> list2 = userMapper.listDynamic("Sam", null);
        Assert.assertNotNull(list2);
        List<UserDO> list3 = userMapper.listDynamic(null, 20);
        Assert.assertNotNull(list3);
        List<UserDO> list4 = userMapper.listDynamic("Sam", 20);
        Assert.assertNotNull(list4);
    }

    /**
     * foreach标签测试
     */
    @Test
    public void queryForeachTag() {
        UserMapper userMapper = getUserMapper();
        List<Long> idList = new ArrayList<>();
        idList.add(1L);
        idList.add(2L);
        List<UserDO> list = userMapper.listForeach(idList);
        Assert.assertNotNull(list);
    }
}
Clone this wiki locally