Mybatis 动态SQL

mybatis-08

实体类

public interface BlogMapper {
    
    //查询博客
    List<Blog> queryBlogIF(Map map);

    List<Blog> queryBlogChoose(Map map);

    //更新博客
    int updateBlog(Map map);

  List<Blog> queryBlogForeach(Map map);
}

动态SQL:

 <!-- 1.IF语句   每一个if都会按顺序执行 -->
    <!--  都要用where标签!!!安全  可以自动识别拼接的语句
            1.如果第一个语句的开始是and或者是or可以自动去除
            2.如何后面没有拼接语句 自己去除where  -->
    <select id="queryBlogIF" parameterType="map" resultType="Blog">
        select * from mybatis.blog
        <where>
            <if test="title!=null">
                title = #{title}
            </if>
            <if test="author!=null">
                and author =#{author}
            </if>
        </where>
    </select>
<!-- 2.choose(when,otherwise)   类似java中的switch  只会按循序执行成立就立即输出(只会成立其中一个)-->
    <select id="queryBlogChoose" parameterType="map" resultType="Blog">
        select * from mybatis.blog
        <where>
            <choose>
                <when test="title !=null">
                    title = #{title}
                </when>
                <when test="author!=null">
                    and author = #{author}
                </when>
                <otherwise>
                    and views= #{views}
                </otherwise>

            </choose>
        </where>
    </select>
 <!-- 3.set语句
            1.用于update会动态前置set关键字
            2.会自动删除无关的逗号
            3.记得拼接语句的时候有的加逗号-->
    <update id="updateBlog" parameterType="map">
        update mybatis.blog
        <set>
            <if test="title!=null">
                title =#{title},
            </if>
            <if test="author!=null">
                author=#{author}
            </if>
        </set>
        where id =#{id}
    </update>
<!-- 4.foreach   -->
    <select id="queryBlogForeach" parameterType="map" resultType="Blog">
        select * from blog
        <where>
            <foreach collection="ids" item="id" open="and (" close=")" separator="or">
                id = #{id}
            </foreach>
        </where>
    </select>

@Test
public void test05(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
HashMap map = new HashMap<String,Object>();

ArrayList<Integer> ids = new ArrayList<>();
ids.add(1);
ids.add(2);
ids.add(3);
map.put("ids",ids);
List<Blog> blogs = mapper.queryBlogForeach(map);
for (Blog blog:blogs) {
System.out.println(blog);
}
sqlSession.close();
}

 

posted @ 2022-10-23 17:30  西东怪  阅读(19)  评论(0编辑  收藏  举报
返回顶端