mybatis之动态sql

什么是动态SQL?
动态SQL指的是根据不同的查询条件 , 生成不同的Sql语句.

  • 新建数据表blog
    在这里插入图片描述

  • 编写实体类对象


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Blog {
    private int id;
    private  String title;
    private String author;
    private int views;
}

  • 核心配置文件中注册mapper
 <mapper class="com.dao.BlobMapper"></mapper>
  • 需求:根据作者名字和博客名字来查询博客!如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询
  • BlogMapper.xml
<mapper namespace="com.dao.BlogMapper">
    <select id="queryBlogIf" resultType="blog" parameterType="map">
        select * from blog
        <where>
            <if test="title != null"> title = #{title} </if>
            <if test="author != null"> and author = #{author} </if>
        </where>
    </select>
</mapper>
  • 测试代码
 @Test
    public void test3(){
        SqlSession session = MybatisUtils.getSession();
        BlogMapper mapper = session.getMapper(BlogMapper.class);
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("title", "java是如此简单");
        List<Blog> blogs = mapper.queryBlogIf(map);
        for(Blog blog : blogs){
            System.out.println(blog);
        }

    }
  • 结果
Blog(id=4, title=Java是如此简单, createTime=Sun Oct 18 16:42:18 CST 2020, author=狂神, views=9999
  • set语句
在这里插入代码片<!--注意set是用的逗号隔开-->
<update id="updateBlog" parameterType="map">
	update blog
	<set>
		<if test="title != null">
			title = #{title},
		</if>
		<if test="author != null">
			author = #{author}
		</if>
	</set>
	where id = #{id};
</update>
  • choose语句:有时候,我们不想用到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用 choose
    标签可以解决此类问题,类似于 Java 的 switch 语句
<select id="queryBlogChoose" parameterType="map" resultType="blog">
	select * from 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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值