您的位置:首页 > 数据库

myBatis学习笔记(6)——动态SQL & 模糊查询

2015-05-12 22:35 731 查看
#动态SQL与模糊查询

<select id="selectUser" parameterType="Map" resultType="User">
        select * from user
        where 1=1
            <if test="name != '%null%' ">
                and username like #{name}
            </if>
            <if test="money != null and money > 0">
                and money <![CDATA[>]]> #{money}
            </if>
    </select>



这里使用到了
<![CDATA[>]]>
表示大于号。大于号和小于号在xml文件中是比较特殊的,不能直接使用,应该
<![CDATA[value]]>
来表示,可以参考spring学习笔记(3)——bean配置细节注意

使用if标签,来动态增加查询的条件

1=1
是为了避免所有条件都会空时,语句错误



查询

SqlSessionFactory factory = MyBatisUtil.getFactory();
        SqlSession session = factory.openSession(true);
        String statement = "com.bank.userMapper.selectUser";
        Map<String,Object> map = new HashMap<String, Object>();
        String name = "o";
        map.put("name", "%"+name+"%");
        map.put("money", 10);
        System.out.println(session.selectList(statement, map));
        session.close();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: