动态SQL

x33g5p2x  于2021-09-24 转载在 其他  
字(3.8k)|赞(0)|评价(0)|浏览(320)

什么是动态SQL:
动态SQL就是指根据不同的条件生成不同的SQL语句

如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。

if
choose (when, otherwise)
trim (where, set)
foreach

搭建环境

CREATE TABLE `blog`(
`id` VARCHAR(50) NOT NULL COMMENT '博客id',
`title` VARCHAR(100) NOT NULL COMMENT '博客标题',
`author` VARCHAR(30) NOT NULL COMMENT '博客作者',
`create_time` DATETIME NOT NULL COMMENT '创建时间',
`views` INT(30) NOT NULL COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8

创建一个基础工程
1.导包

<dependency>
	<groupId>orj.projectlombok</groupId>
	<artifactId>lombok</artifactId>
	<version>1.18.10</version>
</dependency>

2.编写配置文件

<settings>
	<setting name="logImpl" value="STDOUT_LOGGING"/>
	<!--是否开启自动驼峰命名规则(camel case)映射-->
	<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
<mappers>
	<mapper resource="com/jialidun.dao.*"/>
</mappers>

3.编写实体类

@Data
public class Blog{
	private String id;
	private String title;
	private String author;
	private Date createTime;//属性名和字段名不一致
	private int views;

}

4.编写实体类对应的mapper接口和mapper.xml文件

public interface BlogMapper{
	//插入数据
	int addBook(Blog blog);
	//查询博客
	List<Blog> queryBlogIf(Map map);

	
	List<Blog> queryBlogChoose(Map map);

	//更新博客
	int updateBlog(Map map);
}
<mapper namespace="com.jialidun.dao.BlogMapper">
	<insert id="addBlog" parameterType="blog">
		insert into blog(id,title,author,create_time,views) 
		values (#{id},#{title},#{author},#{createTime},#{views});
	</insert>

	<select id="queryBlogIf" parameterType="map" resultType="blog">
		select * from blog(id,title,author,create_time,views)
		where 1=1
		<if test="title != null">
			and title=#{title}
		</if>
		<if test="author != null">
			and author=#{author}
		</if>
	</select>

	
</mapper>

where choose oterwise

<select id="queryBlogChoose" parameterType="map" resultType="blog">
		select * from blog(id,title,author,create_time,views)
		<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>

工具类

@SuppressWarnings("all")//抑制警告
public class IDutils{
	
	public static String getId(){
		return UUID.randomUUID().toString().replaceAll("-","");
	}
	
	@Test
	public void test(){
		System.out.println(IDutils.getId(););
	}

}

测试类;

@Test
 public void addBlogTest(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    Blog blog = new Blog();
    blog.setId(IDutils.getId());
    blog.setTitle(Mybatis);
    blog.setAuthor(RYGAR);
    blog.setCreateTime(new Date());
    blog.setViews(9999);

    mapper.addBook(blog);

    blog.setId(IDutils.getId());
    blog.setTitle(Java);
    mapper.addBook(blog);

    blog.setId(IDutils.getId());
    blog.setTitle(Spring);
    mapper.addBook(blog);

    blog.setId(IDutils.getId());
    blog.setTitle(微服务);
    mapper.addBook(blog);

    sqlSession.close();

SQL片段

有的时候我们可能会将一些功能的部分抽取出来,方便复用!
1.使用SQL标签抽取公共的部分

<sql id="if-title-author">
	<if test="title != null">
		title=#{title}
	</if>
	<if test="author != null">
		and author=#{author}
	</if>
</sql>

2.在需要使用的地方使用include标签引用即可

<select id="queryBlogIf" parameterType="map" resultMap="blog">
	select * from mybatis.blog
	<where>
		<include refid="if-title-author"></include>
	</where>
</select>

注意事项:

  • 最好基于单表来定义SQL片段
  • 不要存在where标签
  • where 条件不成立 没有and,set不成立没有逗号

Foreach

<foreach item="id" collection="ids" open="(" separator="or" close=")">
	#{id}
</foreach>

动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性,按照SQL格式,去排列组合就OK了。
建议:

  • 先在mysql中写出完整的SQL语句,再对应的去修改成为我们的动态SQL

相关文章

微信公众号

最新文章

更多