一、where 和 if标签

1、在IUserDao接口中新建方法

SSM学习之路——Mybatis第三天_动态sql语句教程

2、在IUserDao.xml中编写相应内容

这里的if里面的test为判断的语句条件,里面的参数名字对应java文件里的字段 而不是数据库的
if标签里的内容为sql的语句的拼接
其中where标签其实为 select * from user where 1=1 的改写

特别注意当有多个if的时候,由于标签内容为sql语句的拼接,所以千万不能忘了and 的连接 如下面的
username like #{userName} and sex = …

<select id="findUserByCondition" resultMap="userMap" parameterType="user">
        select  * from user
        <where>
            <if test="userName != null and userName.length() > 0">
                username like #{userName}
            </if>
            <if test="userSex != null and userSex.length() > 0">
                and sex = #{userSex}
            </if>
        </where>
    </select>

还是提一下上面的resultMap为:


<resultMap id="userMap" type="user">
        <id property="userId" column="id"></id>
        <result property="userName" column="username"></result>
        <result property="userBirthday" column="birthday"></result>
        <result property="userSex" column="sex"></result>
        <result property="userAddress" column="address"></result>
    </resultMap>

3、编写测试方法

public void testFindUserByCondition(){
        User user = new User();
        user.setUserName("%老新%");
        user.setUserSex("女");
        List<User> users = userDao.findUserByCondition(user);
        for (User u : users){
            System.out.println(u);
        }
    }

二、foreach和sql标签

1、在IUserDao接口中写方法

返回一个List,传递的参数为QueryVo实体包装类
SSM学习之路——Mybatis第三天_动态sql语句教程

2、在QueryVo实体类中添加字段和get&set

创建一个List,里面全为要查找的id(多个)

private List<Integer> ids = new ArrayList<Integer>();

public List<Integer> getIds() {
    return ids;
}

public void setIds(List<Integer> ids) {
    this.ids = ids;
}

3、编写测试类

创建一个List名为ids,这个名字很重要,下面会提到
其余看注释就行

public void testFindUserByIds(){
    List<Integer> ids = new ArrayList<Integer>();
    //创建一个vo
    QueryVo vo = new QueryVo();
    //往ids列表中添加要查找的id们
    ids.add(67);  
    ids.add(73);  
    ids.add(74);  
    //将ids传给vo实体类
    vo.setIds(ids);
    //产生结果List
    List<User> users = userDao.findUserByIds(vo);
    for (User user: users) {
        System.out.println(user);
    }
}

4、在xml中添加

这里传入的参数为一个queryvo对象
if里的test依然是对应的查找条件

重点

<foreach>标签里面参数解释:
collection:需要传入的集合的对象名
open:条件,注意后面有一个左括号(开括号,所以为open)
item:内容和下面#{id}里的id对应
比如item="id"对应#{id}item="uid"对应#{uid},为传进来的参数的别名,
close:闭括号,与open连用
separator:sql语句多个参数之间的分隔符号,这里为逗号

<select id="findUserByIds" resultMap="userMap" parameterType="queryvo">
    select * from user
    <where>
        <if test="ids != null and ids.size() >0 ">
            <foreach collection="ids" open="and id in (" item="id" close=")" separator=",">
                #{id}
            </foreach>
        </if>
    </where>
</select>

SSM学习之路——Mybatis第三天_动态sql语句教程学个锤子不学了发布了6 篇原创文章 · 获赞 0 · 访问量 51 私信 关注

标签: user, List, sql, SSM, ids, id, Mybatis, vo

相关文章推荐

添加新评论,含*的栏目为必填