Mybatis之动态SQL语句之IF

本文介绍了如何在Mybatis中利用动态SQL的if标签进行多条件查询,通过一个具体的例子展示了如何在BlogMapper接口和mapper.xml中设置查询方法和SQL语句,以及在测试类中执行查询操作。注意在SQL中使用where1=1来避免因条件为空导致的语法错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对于多条件联合查询,可以使用动态SQL之if查询,避免写多个mapper接口多次查询

1、实体类Blog

@Data

public class Blog {
    private String id;
    private String title;
    private String author;
    private Date createTime;
    private int views;
}

2、BlogMapper接口

public interface BlogMapper {
    //查询所有博客信息
    List<Blog> getBlog();

    //添加博客
    int addBlog(Blog blog);

    //根据条件查询,SQL if动态查询,因为是动态查询,所有输入参数为map类型
    List<Blog> queryBlogIf(HashMap map);
}

3、 mapper.xml

    <select id="queryBlogIf" parameterType="map" resultType="com.lizheng.pojo.Blog">
        select * from mybatis.blog where 1=1
        <if test="title != null">
            and title = #{title}
        </if>
        <if test="author != author">
            and author = #{author}
        </if>
    </select>

4、测试类

    @Test
    public void queryBlogTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        map.put("author","狂神说");
        map.put("title","Mybatis");
        mapper.queryBlogIf(map);
        sqlSession.commit();
        sqlSession.close();
    }

5、运行结果

注意点:SQL中IF标签的使用格式;以及where 1=1 (意思是一定执行) ,如果不加上1=1 ,当执行author的时候,SQL语句变成select * from mybatis.blog  and author = #{author} ,这会报错。此时另外一种解决方法就是使用<where><where/>标签。

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值