Mybatis - 动态sql
learn from:http://www.mybatis.org/mybatis-3/dynamic-sql.html
mybatis支持动态拼接sql语句。主要有:
- if
- choose (when, otherwise)
- trim (where, set)
- foreach
1.if
首先看基本实例:
<select id="findActiveBlogWithNameLike" resultType="Blog">
SELECT * FROM blog
WHERE state = 'active'
<if test="name != null">
AND name LIKE #{name}
</if>
</select>
List<Blog> findActiveBlogWithNameLike(String name);
这里遇到一个问题:
There is no getter for property named 'name' in 'class java.lang.String'###
Cause: org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'name' in 'class java.lang.String'
也就是说,mybatis将name当做输入参数的一个属性,并且期望通过getter方法来获取它的值。很容易想到,将输入参数改成Blog就可以了。
然而,这并不符合我们的查询习惯,比如,如果是Blog就必须这样查询:
@Test
public void testFindActiveBlogWithNameLike() throws Exception{
Blog key = new Blog();
key.setName("test%");
List<Blog> blogs = mapper.findActiveBlogWithNameLike(key);
System.out.println(blogs);
return;
}
为了一个String字段而创建一个类,看着要多别扭有多别扭。当然,前提是我们仅仅是查询name条件,所以会觉得其他属性冗余。如果是多条件查询,那么Blog必然是最好的选择。那么,仅仅传入String的话应该也是可以的。参考1,参考2。
第一种做法是简单类型都是使用_parameter来代替。
<select id="findActiveBlogWithNameLikeByString" parameterType="java.lang.String" resultType="Blog">
SELECT * FROM blog
WHERE name LIKE '%${_parameter}%'
</select>
第二种做法比较容易理解,在方法参数前添加@Param(value="xxx")注解来使用xxx作为传入参数。
<select id="findActiveBlogWithNameLikeByString" parameterType="java.lang.String" resultType="Blog">
SELECT * FROM blog
WHERE name LIKE '%${key}%'
</select> List<Blog> findActiveBlogWithNameLikeByString(@Param(value = "key") String key);
两种做法均可,所以,看你喜欢了,是想要省事简洁还是通俗易读。在这里,还是选择第0种方案,即传入Blog对象来作为查询条件。
下面简单介绍if的语法:
- if节点中,属性test是一个boolean值,为true的时候将拼接if里的sql语句。
- 参数值是可以包含一些掩码或通配符的.比如通配符%和占位符_
所以,很简单很容易理解。
场景一: 查询blog的名字name like %Insert and 作者author的username like Ryan%.
首先看期望的结果,blog表中有三条满足name like:
mysql> select * from blog;
+----+------------+-----------+--------------+--------+
| id | name | author_id | co_author_id | state |
+----+------------+-----------+--------------+--------+
| 1 | test | 3 | 4 | active |
| 8 | testInsert | 4 | 5 | active |
| 9 | testInsert | 5 | 6 | active |
| 10 | testInsert | 6 | 7 | active |
| 12 | testA | 50 | NULL | active |
| 13 | testA | 51 | NULL | active |
| 14 | testInsert | NULL | NULL | active |
+----+------------+-----------+--------------+--------+
7 rows in set
这三条中,满足author的username like的有两条:
mysql> select author.id, author.username from author where id in (4,5,6);
+----+----------+
| id | username |
+----+----------+
| 4 | Ryan |
| 5 | Ryan0 |
| 6 | Leslie |
+----+----------+
3 rows in set
也就是我们最终希望结果是blog id为8 和 9。
mybatis的sql语句如下:
<select id="findActiveBlogLike" resultType="Blog">
SELECT * FROM blog b, author a
WHERE state = 'active'
<if test="name != null">
AND name LIKE #{name}
</if>
AND b.author_id = a.id
<if test="author != null and author.name != null">
AND a.username LIKE #{author.username}
</if>
</select>
当blog的name不为null的时候查询name匹配,当author的username不为null的时候,查询author的username匹配。
- 第一个if节点的test为name,这个会查找Blog的name字段,如果传入参数Blog没有name字段,那么就会像我们开始那样报错。所以,name必须是blog的一个字段。同理,#{name}这个也要和blog字段字面量的值匹配。
- 第二个if节点的test里看到了and,and就是并且。首先判断author是否为null,就是判断Blog对象的author属性是否为null。接着判断author.name是否为null,这里就有点问题了。因为我的Author类中并没有name字段,对应的字段字面量是username。也就是说这里应该是author.username。但我粗心写成了author.name(所以为每段代码编写unit test是多么的重要)。更奇葩的是,这条test通过了判断为真,这里先不讲,后面测试的时候再分析原因。不过这里一定要改成author.username才是正确的做法。
对应的java接口:
List<Blog> findActiveBlogLike(Blog blog);
下面开始测试:
@Test
public void testFindActiveBlogLike() throws Exception{
Blog blog = new Blog();
blog.setName("%Insert");
Author author = new Author();
author.setUsername("Ryan%");
blog.setAuthor(author);
List<Blog> blogs = mapper.findActiveBlogLike(blog);
System.out.println(blogs);
assertTrue(blogs.size()==2);
return;
}
先看结果对不对:
2016-08-06 16:20:19,264 DEBUG [org.apache.ibatis.transaction.jdbc.JdbcTransaction] - Opening JDBC Connection
2016-08-06 16:20:19,740 DEBUG [org.apache.ibatis.datasource.pooled.PooledDataSource] - Created connection 1150284200.
2016-08-06 16:20:19,742 DEBUG [org.apache.ibatis.transaction.jdbc.JdbcTransaction] - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@448ff1a8]
2016-08-06 16:20:19,745 DEBUG [com.test.mapper.dao.BlogMapper.findActiveBlogLike] - ==> Preparing: SELECT * FROM blog b, author a WHERE state = 'active' AND name LIKE ? AND b.author_id = a.id AND a.username LIKE ?
2016-08-06 16:20:19,888 DEBUG [com.test.mapper.dao.BlogMapper.findActiveBlogLike] - ==> Parameters: %Insert(String), Ryan%(String)
2016-08-06 16:20:19,978 DEBUG [com.test.mapper.dao.BlogMapper.findActiveBlogLike] - <== Total: 2
[Blog{id=8, name='testInsert', author=null, coAuthor=null, posts=null, state='active'}, Blog{id=9, name='testInsert', author=null, coAuthor=null, posts=null, state='active'}]
test通过了,blog也确实是我们想要的两条。但仔细观察结果就会发现几个问题。第一个问题是author为null,这个我们等下再解决。第二问题是sql查询语句查询了author.username like,也就是说我们第二个if节点的test 为true。难道出了问题?我们的Author类明明没有name字段。所以,这里要跟踪下代码。
好吧,跟踪了半天一直到ognl内部,还是没追踪到为什么name翻译成username了。下面还是搞定第一个问题,author为null。
查询的结果映射到Blog,但blog的author字段并没有初始化。很容易就猜测到结果集的字段和blog的author不匹配。这个就用到resultMap而不是resultType。在上一遍博文中记录了下来。
<select id="findBlogMap" resultMap="findBlogResultMap">
SELECT b.id AS id,
b.name AS name,
b.state AS state,
a.id as author_id,
a.username as author_username,
a.password as author_password,
a.email as author_email,
a.bio as author_bio
FROM blog b, author a
WHERE state = 'active'
<if test="name != null">
AND name LIKE #{name}
</if>
AND b.author_id = a.id
<if test="author != null and author.username != null">
AND a.username LIKE #{author.username}
</if>
</select>
<resultMap id="findBlogResultMap" type="Blog">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="state" column="state"/>
<association property="author" column="author_id" javaType="Author">
<id property="id" column="author_id"/>
<result property="username" column="author_username"/>
<result property="password" column="author_password"/>
<result property="email" column="author_email"/>
<result property="bio" column="author_bio"/>
</association>
</resultMap>
这样测试结果:
-- ::, DEBUG [org.apache.ibatis.transaction.jdbc.JdbcTransaction] - Opening JDBC Connection
-- ::, DEBUG [org.apache.ibatis.datasource.pooled.PooledDataSource] - Created connection .
-- ::, DEBUG [org.apache.ibatis.transaction.jdbc.JdbcTransaction] - Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@]
-- ::, DEBUG [com.test.mapper.dao.BlogMapper.findBlogMap] - ==> Preparing: SELECT b.id AS id, b.name AS name, b.state AS state, a.id as author_id, a.username as author_username, a.password as author_password, a.email as author_email, a.bio as author_bio FROM blog b, author a WHERE state = 'active' AND name LIKE ? AND b.author_id = a.id AND a.username LIKE ?
-- ::, DEBUG [com.test.mapper.dao.BlogMapper.findBlogMap] - ==> Parameters: %Insert(String), Ryan%(String)
-- ::, DEBUG [com.test.mapper.dao.BlogMapper.findBlogMap] - <== Total:
[Blog{id=8, name='testInsert', author=Author{id=4, username='Ryan', password='123456', email='qweqwe@qq.com', bio='this is a blog'}, coAuthor=null, posts=null, state='active'}, Blog{id=9, name='testInsert', author=Author{id=5, username='Ryan0', password='123456', email='qweqwe@qq.com', bio='this is a blog'}, coAuthor=null, posts=null, state='active'}]
2.choose
Mybatis - 动态sql的更多相关文章
- mybatis实战教程(mybatis in action)之八:mybatis 动态sql语句
mybatis 的动态sql语句是基于OGNL表达式的.可以方便的在 sql 语句中实现某些逻辑. 总体说来mybatis 动态SQL 语句主要有以下几类:1. if 语句 (简单的条件判断)2. c ...
- 9.mybatis动态SQL标签的用法
mybatis动态SQL标签的用法 动态 SQL MyBatis 的强大特性之一便是它的动态 SQL.如果你有使用 JDBC 或其他类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句有多么 ...
- 自己动手实现mybatis动态sql
发现要坚持写博客真的是一件很困难的事情,各种原因都会导致顾不上博客.本来打算写自己动手实现orm,看看时间,还是先实现一个动态sql,下次有时间再补上orm完整的实现吧. 用过mybatis的人,估计 ...
- Mybatis动态SQL单一基础类型参数用if标签
Mybatis动态SQL单一基础类型参数用if标签时,test中应该用 _parameter,如: 1 2 3 4 5 6 <select id="selectByName" ...
- 超全MyBatis动态SQL详解!( 看完SQL爽多了)
MyBatis 令人喜欢的一大特性就是动态 SQL. 在使用 JDBC 的过程中, 根据条件进行 SQL 的拼接是很麻烦且很容易出错的. MyBatis 动态 SQL 的出现, 解决了这个麻烦. My ...
- Mybatis动态SQL简单了解 Mybatis简介(四)
动态SQL概况 MyBatis 的强大特性之一便是它的动态 SQL 在Java开发中经常遇到条件判断,比如: if(x>0){ //执行一些逻辑........ } Mybatis应用中,S ...
- mybatis原理分析学习记录,mybatis动态sql学习记录
以下个人学习笔记,仅供参考,欢迎指正. MyBatis 是支持定制化 SQL.存储过程以及高级映射的持久层框架,其主要就完成2件事情: 封装JDBC操作 利用反射打通Java类与SQL语句之间的相互转 ...
- mybatis 动态sql和参数
mybatis 动态sql 名词解析 OGNL表达式 OGNL,全称为Object-Graph Navigation Language,它是一个功能强大的表达式语言,用来获取和设置Java对象的属性, ...
- MyBatis动态SQL之一使用 if 标签和 choose标签
bootstrap react https://segmentfault.com/a/1190000010383464 xml 中 < 转义 to thi tha <if test=&qu ...
- MyBatis动态SQL(认真看看, 以后写SQL就爽多了)
目录 0 一起来学习 mybatis 1 数据准备 2 if 标签 2.1 在 WHERE 条件中使用 if 标签 2.1.1 查询条件 2.1.2 动态 SQL 2.1.3 测试 2.2 在 UPD ...
随机推荐
- 一鼓作气 博客--第二篇 note2
1.循环正常结束是指没有中间截断,即没有执行break; for i in range(10) print(i) else: print("循环正常结束") 2.嵌套循环 for ...
- jquery如何获取第一个或最后一个子元素?
通过children方法,children("input:first-child") 1 2 $(this).children("input:first-child&qu ...
- iOS开发中手机号码和价格金额有效性判断及特殊字符的限制
在实际开发过程中,经常会遇到些不能让用户随便地输入手机号码,对输入的手机号码的正确判断:有些输入框只能输入数字,不能输入字母或特殊字符:还有些如价格金额之类的就只能输入数字和小数点且小数点后面保留两位 ...
- [Voice communications] 音量的控制
改变音频的音量是音频处理中最基础的部分,我们可以利用 GainNode 来构建 Mixers 的结构块.GainNode 的接口是很简单的: interface GainNode : AudioNod ...
- MySQL 远程连接(federated存储引擎)
标签:federated存储引擎 概述 本文主要介绍通过federated存储引擎建立远程连接表 测试环境:mysql 5.6.21 步骤 开启federated存储引擎 先查看federated存储 ...
- shell使用攻略
shell 是什么 ~ $ ls /bin/*sh /bin/bash /bin/csh /bin/ksh /bin/sh /bin/tcsh /bin/zsh 是什么 kernel shell 命令 ...
- Java抽象类的总结
什么是抽象类: 当你在定义一个父级的类的时候,往往在父级内的方法没有添加任何内容,这时候如果你在子类里面调用父级的时候,万一在子类之中类名或者方法名没有写正确,会出现不执行的情况,但是这种情况默认是不 ...
- 设有一数据库,包括四个表:学生表(Student)、课程表(Course)、成绩表(Score)以及教师信息表(Teacher)。
一. 设有一数据库,包括四个表:学生表(Student).课程表(Course).成绩表(Score)以及教师信息表(Teacher).四个表的结构分别如表1-1的表(一)~表( ...
- 【WP8.1开发】用手机来控制电脑的多媒体播放
为了用电脑看电影时方便控制,我就突发其想,做一个手机app来通过无线网络远程调节电脑上的音量.后来进行尝试成功后,我就想,光是调音量似乎单调了些,就把播放/暂停,上一首,下一首,等多媒体控制功能也加上 ...
- 分享几个.NET WinForm开源组件,纪念逐渐远去的WinForm。。。
前面3个月的时间内,这些.NET开源项目你知道吗?系列文章已经发表了3篇,共计45个平时接触比较少,曾经默默无闻的.NET开源项目,展示给大家,当然不是每个人都能用得上,但也的确是有些人用了,反响还不 ...