Mybatis动态SQL之IF语句

本文介绍了Mybatis中如何使用IF语句进行动态SQL构建,通过示例展示了在实体类、接口、mapper配置文件及测试类中的具体实现。在不同条件下,IF语句控制SQL语句的拼接,当条件满足时追加特定查询条件。

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

Mybatis动态SQL之IF语句

直接先给核心代码块:

    <select id="queryBlogIf" parameterType="map" resultType="Blog">
        select * from mybatis.blog where 1=1
        <if test="title!=null">
            <!--如果title不为空,追加下方代码-->
            and title=#{title}
        </if>
        <if test="author!=null">
            <!--如果author不为空,追加下方代码-->
            and author=#{author}
        </if>
    </select>

Mybatis中,我们通过if语句实现动态SQL,使用方法如下

<if test="这里写判断内容">
“这里写要追加的sql代码”
</if>

如果上方代码还有疑问,可以看下面大致项目的实现代码:
实体类(Blog博客类)及属性定义:

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

接口类定义:

public interface BlogMapper {
    List<Blog> queryBlogIf(Map map);//查询博客的方法
}

mapper配置文件:


<insert id="addBlog" parameterType="com.zm.pojo.Blog">
        insert into mybatis.blog (id, title, author, views, create_time)
        values (#{id},#{title},#{author},#{views},#{createTime})
</insert>

    <select id="queryBlogIf" parameterType="map" resultType="Blog">
        select * from mybatis.blog where 1=1
        <if test="title!=null">
            <!--如果title不为空,追加下方代码-->
            and title=#{title}
        </if>
        <if test="author!=null">
            <!--如果author不为空,追加下方代码-->
            and author=#{author}
        </if>
    </select>

测试类方法:

	@Test
    public void test2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();//建立一个SqlSession对象
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map =new HashMap();
        map.put("title","Java");//追加一个title值,令查询结果的title均为Java
        List<Blog> blogs=mapper.queryBlogIf(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
    }

数据库内容如下:
在这里插入图片描述
上述代码查询结果如下:
在这里插入图片描述

我们试一试如果在测试类里不给map添加内容,结果会怎样。

@Test
    public void test2(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();//建立一个SqlSession对象
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map =new HashMap();//传入一个空map
        List<Blog> blogs=mapper.queryBlogIf(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
    }

结果如下:
在这里插入图片描述
当map为空,那么我们if中的判断是不成立的,那么就没有追加代码,即sql只执行了这句代码:

select * from mybatis.blog where 1=1

而当我们给map赋值:
map.put(“title”,“Java”);

sql语句则被追加了内容,最后结果变为:

select * from mybatis.blog where 1=1 and title=#{title}

、创作不易,点个赞哦。如发现有错误,请评论指正。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值