学习MyBatis必知必会(7)~注解开发、动态SQL
一、MyBatis的注解开发
- 开发中推荐是使用xml文件配置
1、配置映射关系【使用注解的方式】:
<!-- 全局的配置文件 -->
<configuration>
<!-- 2、关联映射文件/ 关联Mapper接口 -->
<mappers>
<!-- <mapper resource="com/shan/hello/mapper/UserMapper.xml"/>-->
<mapper class="com.shan.hello.mapper.UserMapper"/>
</mappers>
</configuration>
2、通过注解,把sql和映射写到Mapper接口:
public interface UserMapper {
@Insert("insert into t_user (name, salary) values (#{name}, #{salary});")
@Options(useGeneratedKeys = true,keyProperty = "id")
void save(User user);
@Delete("delete from t_user where id = #{id};")
void delete(Long id);
@Update("update t_user set name = #{name}, salary = #{salary} where id = #{id};")
void update(User user);
// void update(User user, Long id);//错误:myBatis默认只能传递一个参数
@Select("select id u_id, name as u_name, salary u_salary from t_user where id = #{id}")
@Results(id="BaseResultMap", value= {
@Result(column = "u_id",property = "id"),
@Result(column = "u_name",property = "name"),
@Result(column = "u_salary",property = "salary")
})
User get(Long id);
@Select("select id u_id, name as u_name, salary u_salary from t_user")
@ResultMap("BaseResultMap")
List<User> getListAll();
}
3、测试(这里以测试查询为例):
/* 测试查询 */
@Test
public void testGet() throws IOException {
SqlSession session = MyBatisUtil.getSession();
UserMapper userMapper = session.getMapper(UserMapper.class);
User user = userMapper.get(2L);
System.out.println(user);
//5、关闭资源
session.close();
}
二、动态SQL 【类似JSTL(java标准标签库)语法】
if
choose (when, otherwise)
trim (where, set)
foreach
其他(bind,sql,include)
1、if 举例:
<!-- 映射文件 -->
<select id="select" resultType="Employee">
select * from employee
<if test="minSalary != null">
where salary >= #{minSalary}
</if>
</select>
细节:在xml中 小于符合不能直接输入 < , 会被当做标签的开始标志,需要使用转义符号 <;
防止第一个查询条件是null,加上 where 1=1,然后其他查询条件接着and 写。
2、choose (when, otherwise) 举例:
<!-- 映射文件 -->
<select id="select" resultType="Employee">
select * from employee where 1=1
<if test="minSalary != null">
and salary >= #{minSalary}
</if>
<choose>
<when test="deptId > 0">and deptId = #{deptId}</when>
<otherwise>and deptId is not null</otherwise>
</choose>
</select>
3-1、trim (where, set)- where 举例:
解决sql拼接查询条件时第一个条件为null,而加上 where 1=1,导致不能进行索引查询,影响性能。
where 元素:判断查询条件是否有where关键字,若没有,则第一个查询条件之前要插入 where
若发现查询条件是以and/or开头,则会把第一个查询条件前的and/or 替换成 where
<!-- 映射文件 -->
<select id="select" resultType="Employee">
select * from employee
<where>
<if test="minSalary != null">
and salary >= #{minSalary}
</if>
<if test="maxSalary != null">
and salary <= #{maxSalary}
</if>
<choose>
<when test="deptId > 0">and deptId = #{deptId}</when>
<otherwise>and deptId is not null</otherwise>
</choose>
</where>
</select>
3-2、trim (where, set)-set 举例:
- 和where 类似,动态去掉最后一个逗号
<update id="updateAuthorIfNecessary">
update Author
<set>
<if test="username != null">username=#{username},</if>
<if test="password != null">password=#{password},</if>
<if test="email != null">email=#{email},</if>
<if test="bio != null">bio=#{bio}</if>
</set>
where id=#{id}
</update>
3-3、trim (where, set)-trim :
<trim prefix="" prefixOverrides="" suffix="" suffixOverrides="">
<!--trim 包含的动态 SQL-->
</trim>
□ prefix – 在这个字符串之前插入 prefix 属性值。
□ prefixOverrides – 并且字符串的内容以 prefixOverrides 中的内容开头(可以包含管道符号),那么使用 prefix 属性值替换内容的开头。
□ suffix – 在这个字符串之后插入 suffix 属性值。
□ suffixOverrides –并且字符串的内容以 suffixOverrides 中的内容结尾(可以包含管道符号),那么使用 suffix 属性值替换内容的结尾。
使用 where 等价于: 注意:此时 AND 后面有一个空格。
使用 set 等价于:
4、foreach 举例1:
/* Mapper接口 */
void batchDelete(@Param("ids")List<Long> ids);
<!-- 映射文件 -->
<!--
foreach 元素: collection属性:表示要迭代的集合或数组【的类型,若是通过Parm注解,可以直接写上Map中的key,而不用填写类型】
open属性:在集合迭代之前,要拼接的符号 close 属性:在集合迭代之后要拼接的符号
separator属性:迭代的元素之间的分割符号
item属性:每个被迭代的元素
index属性:迭代的索引
-->
<delete id="batchDelete">
delete from employee where id in
<foreach collection="ids" open="(" close=")" separator="," item="id">
#{id}
</foreach>
</delete>
■ foreach 举例2:
/* Mapper接口 */
void batchSave(@Param("emps")List<Employee>emps);
<!-- 映射文件 -->
<insert id="batchSave">
insert into employee (name, sn, salary) values
<foreach collection="emps" separator="," item="e">
(#{e.name}, #{e.sn}, #{e.salary})
</foreach>
</insert>
5、其他(bind,sql,include) 举例-高级分页查询:
■ sql,include 的例子:
<!-- 映射文件 -->
<mapper namespace="com.shan.hello.mapper.EmployeeMapper">
<sql id="base_where">
<where>
<if test="keyword != null">
<!--and name like #{%name%}; 要使用字符串函数concat进行拼接呀 -->
<!-- and name like concat('%', #{name}, '%') or sn like concat('%', #{sn},'%'); qo查询对象,也没有属性name,sn呀 -->
and (name like concat('%', #{keyword}, '%') or sn like concat('%', #{keyword}, '%'))
</if>
<if test="minSalary != null">
and salary >= #{minSalary}
</if>
<if test="maxSalary != null">
and salary <= #{maxSalary}
</if>
<if test="deptId > 0">
and deptId = #{deptId}
</if>
</where>
</sql>
<select id="queryForList" resultType="Employee">
select id, name, sn, salary from employee
<include refid="base_where"/>
</select>
<select id="queryForCount" resultType="int">
select count(id) from employee
<include refid="base_where"/>
</select>
</mapper>
■ bind(跟concat一样是用于拼接字符串) 的例子:
<if test="keyword != null">
<!--and name like #{%name%}; 要使用字符串函数concat进行拼接呀 -->
<!-- and name like concat('%', #{name}, '%') or sn like concat('%', #{sn},'%'); qo查询对象,也没有属性name,sn呀 -->
<!-- and (name like concat('%', #{keyword}, '%') or sn like concat('%', #{keyword}, '%')) -->
<bind name="keywordLike" value="'%' + keyword + '%'"/>
and (name like #{keywordLike} or sn like #{keywordLike})
</if>
学习MyBatis必知必会(7)~注解开发、动态SQL的更多相关文章
- 后端框架的学习----mybatis框架(7、使用注解开发)
7.使用注解开发 1.注解在接口上实现 /** * 查询用户 */ @Select("select * from user") public List<User> ge ...
- mybatis注解开发-动态SQL
实体类以及表结构 在mybatis-config.xml中注册mapper接口 -------------------------- 动态查询@SelectProvider EmployeeMappe ...
- [ 学习路线 ] 2015 前端(JS)工程师必知必会 (2)
http://segmentfault.com/a/1190000002678515?utm_source=Weibo&utm_medium=shareLink&utm_campaig ...
- 《SQL必知必会》学习笔记二)
<SQL必知必会>学习笔记(二) 咱们接着上一篇的内容继续.这一篇主要回顾子查询,联合查询,复制表这三类内容. 上一部分基本上都是简单的Select查询,即从单个数据库表中检索数据的单条语 ...
- 学习《SQL必知必会(第4版)》中文PDF+英文PDF+代码++福达BenForta(作者)
不管是数据分析还是Web程序开发,都会接触到数据库,SQL语法简洁,使用方式灵活,功能强大,已经成为当今程序员不可或缺的技能. 推荐学习<SQL必知必会(第4版)>,内容丰富,文字简洁明快 ...
- 《MySQL必知必会》学习笔记——前言
前言 MySQL已经成为世界上最受欢迎的数据库管理系统之一.无论是用在小型开发项目上,还是用来构建那些声名显赫的网站,MySQL都证明了自己是个稳定.可靠.快速.可信的系统,足以胜任任何数据存储业务的 ...
- 必知必会之Java注解
必知必会之Java注解 目录 不定期更新中-- 元注解 @Documented @Indexed @Retention @Target 常用注解 @Deprecated @FunctionalInte ...
- 《SQL必知必会》学习笔记整理
简介 本笔记目前已包含 <SQL必知必会>中的所有章节. 我在整理笔记时所考虑的是:在笔记记完后,当我需要查找某个知识点时,不需要到书中去找,只需查看笔记即可找到相关知识点.因此在整理笔记 ...
- 《SQL必知必会》学习笔记(一)
这两天看了<SQL必知必会>第四版这本书,并照着书上做了不少实验,也对以前的概念有得新的认识,也发现以前自己有得地方理解错了.我采用的数据库是SQL Server2012.数据库中有一张比 ...
- mysql学习--mysql必知必会1
例如以下为mysql必知必会第九章開始: 正則表達式用于匹配特殊的字符集合.mysql通过where子句对正則表達式提供初步的支持. keywordregexp用来表示后面跟的东西作为正則表達式 ...
随机推荐
- 一个网关服务性能问题的Dump分析
本篇文章分为三部分,首先简单介绍一下分析的工具Windbg,其次针对一个网关服务性能问题进行逐步刨析,最后针对性能问题的分析总结. 一 Windbg介绍 1.Windbg是个非常强大的调试器,它设计了 ...
- 第二十七个知识点:什么是对称密码加密的AEAD安全定义?
第二十七个知识点:什么是对称密码加密的AEAD安全定义? AEAD 在之前的博客里,Luke描述了一种被广泛使用的操作模式(ECB,CBC和CTR)对块密码.我们也可能会想我们加密方案的完整性,完整性 ...
- FineGAN
目录 概 主要内容 隐变量 背景 轮廓 色彩和纹理 用于无监督分类 代码 Singh K., Ojha U. & Lee Y. FineGAN: Unsupervised Hierarchic ...
- 基于Java swing+mysql+eclipse的【水电费管理系统】
本项目为前几天收费帮学妹做的一个项目,Java swing项目,在工作环境中基本使用不到,但是很多学校把这个当做编程入门的项目来做,故分享出本项目供初学者参考. CSDN9.9赞助下载: https: ...
- Java Web程序设计笔记 • 【第8章 会话跟踪技术进阶】
全部章节 >>>> 本章目录 8.1 Session机制 8.1.1 Session 简介 8.1.2 创建 HttpSession 实例 8.1.3 HttpSesiso ...
- 云南农业职业技术学院 / 互联网技术学院官网 HTML5+CSS3
HTML学完后写了,有小组成员参与开发,我只写了主页,那就只贴主页的代码出来了. 作为初学者,代码写得不太好,写博客纯属记录!有问题望指导! 码云开源仓库地址:https://gitee.com/yn ...
- SpringBoot中如何优雅的使用多线程
SpringBoot中如何优雅的使用多线程 当异步方法有返回值时,如何获取异步方法执行的返回结果呢?这时需要异步调用的方法带有返回值CompletableFuture
- AWS修改RDS时区
查看 RDS 当前时区 默认情况下,AWS 的 RDS 采用的是 UTC 时间.而我们地区一般位于东八区,因此我们本地的时间是 UTC+8. 连接到 RDS 上,查询当前实例的时区. show var ...
- js- float类型相减 出现无限小数的问题
6.3 -1.1 是不是应该等于5.2? 但是js 会导致得出 5.19999999999的结果 怎么办?可以先先乘100 后相减,然是用方法 舍入为最接近的整数,然后再除于100, Math.rou ...
- redis中文乱码问题
1.可以直接打开dos指令框输入指令进去redis数据库,因为在安装的时候就已经勾选了配置默认的环境变量. 2.可以输入ip进去,redis-cli.exe -h 192.168.32.8 -p 63 ...