MyBatis 实践 -动态SQL/关联查询
标签: Java与存储
动态SQL
动态SQL提供了对SQL语句的灵活操作,通过表达式进行判断,对SQL进行拼接/组装.
if
对查询条件进行判断,如果输入参数不为空才进行查询条件的拼接.
- mapper
<select id="selectUser" resultType="com.fq.domain.User" parameterType="com.fq.domain.User">SELECT * FROM user<where><if test="id != null">AND id = #{id}</if><if test="name != null">AND name = #{name}</if><if test="password != null">AND password = #{password}</if></where>
</select>
<where/>
会自动处理第一个AND
(MyBatis还提供了自定义<where/>
行为的<trim/>
元素, 详细可参考MyBatis文档).
- UserDAO
List<User> selectUser(User user) throws Exception;
- Client
@Test
public void selectUserClient() throws Exception {UserDAO dao = session.getMapper(UserDAO.class);User user = dao.selectUser(new User(null, null, "new_password"));System.out.println(user);
}
由于id与name为
null
, 因此这两个条件不会拼接在SQL中,这一点可以调试时日志中看出.
choose/when/otherwise
有些时候,我们并不想用到所有的条件语句,而只想从中选择一二.针对这种情况,MyBatis提供了<choose/>
元素,他有点像Java中的switch
.
<select id="selectUser" resultType="com.fq.domain.User" parameterType="com.fq.domain.User">SELECT * FROM user<where><choose><when test="id != null">AND id = #{id}</when><when test="name != null">AND name = #{name}</when><otherwise>AND password = #{password}</otherwise></choose></where>
</select>
set
用于动态更新语句的解决方案为<set/>
,set元素可以被用于动态包含需要更新的列, 而舍去其他的.
<update id="updateUserById" parameterType="com.fq.domain.User">UPDATE user<set><if test="name != null">name = #{name} ,</if><if test="password != null">password = #{password} ,</if></set>WHERE id = #{id};
</update>
foreach
使用foreach可以实现向SQL中传递数组或List
:
传入List
查询多个id的用户信息, 可以由下面两种SQL实现:
SELECT * FROM user WHERE (id = ? OR id = ? OR id = ?);
SELECT * FROM user WHERE id IN (?, ?, ?, ?);
因此其foreach的定义也有如下两种方案:
<select id="selectUser" parameterType="java.util.List" resultType="com.fq.domain.User">SELECT *FROM user<where><if test="list != null and list.size >= 1"><foreach collection="list" item="id" open="(" separator="or" close=")">id = #{id}</foreach></if></where>
</select>
<select id="selectUser" parameterType="java.util.List" resultType="com.fq.domain.User">SELECT *FROM user<where><if test="list != null and list.size >= 1"><foreach collection="list" item="id" open="id IN (" separator="," close=")">#{id}</foreach></if></where>
</select>
元素 | 描述 |
---|---|
collection
|
SQL解析的参数名 |
index
|
循环下标 |
item
|
单个元素的名 |
open
|
循环开始输出 |
close
|
循环结束输出 |
separator
|
中间分隔输出 |
传递
List
作为parameterType
时,SQL解析参数名固定为list
.
- UserDAO
List<User> selectUser(List<Integer> ids) throws Exception;
批量插入用户案例
- mapper
<insert id="insertUserList" parameterType="java.util.List">INSERT INTO user(name, password) VALUES<if test="list != null and list.size != 0"><foreach collection="list" item="user" separator=",">(#{user.name}, #{user.password})</foreach></if>
</insert>
- UserDAO
void insertUserList(List<User> users) throws Exception;
- Client
@Test
public void insertUserListClient() throws Exception {UserDAO dao = session.getMapper(UserDAO.class);dao.insertUserList(Lists.newArrayList(new User(null, "mojia5", "mojia5"), new User(null, "mojia6", "mojia6"), new User(null, "mojia7", "mojia7")));
}
传入数组
- mapper
<select id="selectUser" parameterType="Object[]" resultType="com.fq.domain.User">SELECT *FROM user<where><if test="array != null and array.length >= 1"><foreach collection="array" item="id" open="id IN (" separator="," close=")">#{id}</foreach></if></where>
</select>
与
List
类似,传递数组作为parameterType
时,SQL解析参数名固定为array
.
- UserDAO
List<User> selectUser(Integer[] ids) throws Exception;
SQL片段
可以将一段公共的SQL语句抽取出来, 作为一个SQL片段, 供其他SQL调用:
<sql id="user_where"><if test="id != null">AND id = #{id}</if><if test="name != null">AND name = #{name}</if><if test="password != null">AND password = #{password}</if>
</sql><select id="selectUser" resultType="com.fq.domain.User" parameterType="com.fq.domain.User">SELECT * FROM user<where><include refid="user_where"/></where>
</select>
经验:最好基于单表定义SQL片段,而且在SQL片段中不要包含
<where>
/<set>
之类的标签,这样可以保证SQL片段重用度更高.
关联查询
数据模型分析思路
- 每张表的数据内容:分模块对每张表记录的内容进行熟悉,相当于学习系统需求/功能.
- 每张表重要的字段:非空字段/外键字段等.
- 表与表之间的数据库级别关系: 外键关系.
- 表与表之间的业务关系:建立在某个业务的基础上去分析.
订单/商品数据模型
- 表内容
- user: 购买商品的用户信息
- order: 用户创建的订单
- orderdetail: 订单详细(购买商品信息)
- item: 商品信息
- 表与表之间的业务关系:
- user/order:
- user -> order: 一对多
- order -> user: 一对一
- order/orderdetail:
- order -> orderdetail:一对多
- orderdetail -> order:一对一
- orderdetail/item:
- orderdetail -> item:一对一
- item -> orderdetail:一对多
- user/order:
- 表内容
‘一对一’查询
需求: 查询订单信息,关联查询(创建订单的)用户信息.
由以上分析可知主查询为order
表,而order -> user
关系为一对一, 因此使用resultMap
将查询结果的订单信息映射到Order
中,将用户信息映射到Order
中的User
属性.
- PO: 改造
User
public class User implements Serializable {private Integer id;private String username;private Date birthday;private Integer sex;private String address;// ...
}
- PO: 新增
Order
, 将User
组合到Order
中:
public class Order implements Serializable {private Integer id;private Integer userId;private String number;private Date createTime;private String note;private User user;// ...
}
- mapper
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fq.mybatis.OrderDAO"><cache type="org.mybatis.caches.ehcache.EhcacheCache"/><resultMap id="order_user_map" type="com.fq.domain.Order"><id column="id" property="id"/><result column="user_id" property="userId"/><result column="number" property="number"/><result column="create_time" property="createTime"/><result column="note" property="note"/><association property="user" javaType="com.fq.domain.User"><id column="user_id" property="id"/><result column="username" property="username"/><result column="birthday" property="birthday"/><result column="sex" property="sex"/><result column="address" property="address"/></association></resultMap><select id="selectOrderWithUser" resultMap="order_user_map">SELECT`order`.*,username,birthday,sex,addressFROM `order`, userWHERE `order`.user_id = user.id AND `order`.id = #{0};</select></mapper>
association
: 映射关联查询的单条记录(将关联查询信息映射到PO对象属性).
- OrderDAO
public interface OrderDAO {Order selectOrderWithUser(Integer id) throws Exception;
}
- Client
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext.xml")
public class OrderDAOClient {@Autowiredprivate OrderDAO dao;@Testpublic void client() throws Exception {Order order = dao.selectOrderWithUser(3);System.out.println(order);}
}
‘一对多’查询
需求: 查询订单及订单明细的信息(一对多).
- PO: 定义
OrderDetail
,并在Order
中添加List<OrderDetail> orderDetails
订单明细属性:
public class OrderDetail implements Serializable {private Integer id;private Integer orderId;private Integer itemId;private Integer itemNumber;// ...
}
- mapper
<resultMap id="order_user_detail_map" type="com.fq.domain.Order" extends="order_user_map"><collection property="orderDetails" ofType="com.fq.domain.OrderDetail"><id column="order_detail_id" property="id"/><result column="item_id" property="itemId"/><result column="item_num" property="itemNumber"/><result column="order_id" property="orderId"/></collection>
</resultMap><select id="selectOrderWithDetail" resultMap="order_user_detail_map">SELECT`order`.*,username,birthday,sex,address,orderdetail.id order_detail_id,item_id,item_num,order_idFROM `order`, user, orderdetailWHERE `order`.user_id = user.id AND `order`.id = orderdetail.order_id AND `order`.id = #{0};
</select>
元素 | 描述 |
---|---|
property
|
指定关联查询的结果集存储到的属性 |
ofType
|
指定关联查询结果集中的对象类型 |
- OrderDAO
Order selectOrderWithDetail(Integer id) throws Exception;
‘多对多’查询
需求: 查询用户及用户购买商品信息.
由于User表与Item表没有直接关联,因此只能通过Order表与OrderDetail表进行关联.
思路:
1) 将用户信息映射到User
中.
2) 在User
中添加List<Order>
订单列表属性,将用户创建的订单映射到orders
.
3) 在Order
中添加List<OrderDetail>
订单明细列表属性,将订单的明细映射到orderDetails
.
4) 在OrderDetail
中添加Item
属性,将订单明细所对应的商品映射到item
.PO: Item
public class Item {private Integer id;private String name;private Float price;private String detail;private String pic;private Date createTime;//...
}
- mapper
<resultMap id="user_item_map" type="com.fq.domain.User"><id column="id" property="id"/><result column="username" property="username"/><result column="birthday" property="birthday"/><result column="sex" property="sex"/><result column="address" property="address"/><collection property="orders" ofType="com.fq.domain.Order"><id column="order_id" property="id"/><result column="id" property="userId"/><result column="order_create_time" property="createTime"/><result column="order_note" property="note"/><result column="order_number" property="number"/><collection property="orderDetails" ofType="com.fq.domain.OrderDetail"><id column="order_detail_id" property="id"/><result column="order_id" property="orderId"/><result column="item_id" property="itemId"/><result column="order_item_num" property="itemNumber"/><association property="item" javaType="com.fq.domain.Item"><id column="item_id" property="id"/><result column="item_create_time" property="createTime"/><result column="item_detail" property="detail"/><result column="item_name" property="name"/><result column="item_price" property="price"/><result column="item_pic" property="pic"/></association></collection></collection>
</resultMap><select id="selectUserItem" resultMap="user_item_map">SELECTuser.*,`order`.id order_id,`order`.create_time order_create_time,`order`.note order_note,`order`.number order_number,orderdetail.id order_detail_id,orderdetail.item_num order_item_num,item.id item_id,item.create_time item_create_time,item.detail item_detail,item.name item_name,item.price item_price,item.pic item_picFROM user, item, `order`, orderdetailWHERE `order`.user_id = user.id AND orderdetail.order_id = `order`.id AND orderdetail.item_id = item.id ;
</select>
- OrderDAO
List<User> selectUserItem() throws Exception;
resultMap小结:
使用<association/>
和<collection/>
可以完成一对一和一对多的高级映射.
- association: 将关联查询信息映射到一个PO对象中.
- collection: 将关联查询信息映射到一个集合中.
延迟加载
关联查询时,使用MyBatis 延迟加载 特性可有效减轻数据库压力.首次查询只查询主表信息,等需要时再去查询关联表信息.<resultMap/>
的<association/>
/<collection/>
具备延迟加载功能.
需求: 查询订单信息并关联查询用户信息.
延迟加载开关
在MyBatis核心配置文件(mybatis-configuration.xml)中配置:
1)lazyLoadingEnabled
: 设置是否懒加载.默认false
,则所有关联查询都会被初始化加载.
2)aggressiveLazyLoading
: 设置是否积极加载. 默认true
,所有关联属性被初始化加载.Settings配置:
<settings><setting name="cacheEnabled" value="true"/><setting name="lazyLoadingEnabled" value="true"/><setting name="aggressiveLazyLoading" value="false"/>
</settings>
Mapper
- 只查询订单信息
<resultMap id="order_user_map" type="com.fq.domain.Order"><id column="id" property="id"/><result column="user_id" property="userId"/><result column="number" property="number"/><result column="create_time" property="createTime"/><result column="note" property="note"/><association property="user" javaType="com.fq.domain.User" select="com.fq.mybatis.UserDAO.selectUserById" column="user_id"/>
</resultMap><select id="selectOrderWithUser" resultMap="order_user_map">SELECT *FROM `order`;
</select>
元素 | 描述 |
---|---|
select
|
指定关联查询Statement为com.fq.mybatis.UserDAO.selectUserById .
|
column
|
指定关联查询时将users_id 值传入selectUserById .
|
- 关联查询用户信息(namespace为
com.fq.mybatis.UserDAO
)
<select id="selectUserById" parameterType="java.lang.Integer" resultType="com.fq.domain.User">SELECT *FROM userWHERE id = #{id};
</select>
将上面查询到的订单信息中的
user_id
传入selectUserById
来关联查询用户信息.
- OrderDAO(同前)
List<Order> selectOrderWithUser() throws Exception;
- Client
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/applicationContext.xml")
public class OrderDAOClient {@Autowiredprivate OrderDAO dao;@Testpublic void client() throws Exception {List<Order> orders = dao.selectOrderWithUser();for (Order order : orders) {System.out.println(order.getUser());}}
}
debug上面
Client
, 观察log信息,会发现只有当确实需要User
信息时才会调用selectUserById
.
转载于:https://www.cnblogs.com/itrena/p/5926903.html
MyBatis 实践 -动态SQL/关联查询相关推荐
- mybatis collection标签_MyBatis第二天(结果映射+动态sql+关联查询)
笑不出莱:MyBatis第一天(介绍+文件配置+Mapper动态代理)zhuanlan.zhihu.com 一.导包+配置文件+pojo类 1.jar包:mybatis的核心包和依赖包+连接数据库的 ...
- mybatis02映射动态sql关联查询spring整合mybatis
2019独角兽企业重金招聘Python工程师标准>>> 输入映射和输出映射: 动态sql: 关联查询_一对一: 关联查询_一对多: 一对一,一对多操作的区别: 一对一,resultM ...
- Mybatis:动态SQL分组查询
目录 1. 实现思路 2. 代码实现 2.1 mapper 2.2 mapper 接口 2.3 Service层 AjaxResult对象 2.4 controller 2.5 测试 1. 实现 ...
- 【MyBatis】 动态SQL——模糊查询 LIKE
一.like '%?%' SELECT * FROM t_usr WHERE name like '%${name}%' SQL解析为:SELECT * FROM t_usr WHERE name l ...
- 利用MyBatis的动态SQL特性抽象统一SQL查询接口
1. SQL查询的统一抽象 MyBatis制动动态SQL的构造,利用动态SQL和自定义的参数Bean抽象,可以将绝大部分SQL查询抽象为一个统一接口,查询参数使用一个自定义bean继承Map,使用映射 ...
- java day55【 Mybatis 连接池与事务深入 、 Mybatis 的动态 SQL 语句、 Mybatis 多表查询之一对多 、 Mybatis 多表查询之多对多】...
第1章 Mybatis 连接池与事务深入 1.1 Mybatis 的连接池技术 1.1.1 Mybatis 连接池的分类 1.1.2 Mybatis 中数据源的配置 1.1.3 Mybatis 中 D ...
- MyBatis中动态sql实现时间范围比较的查询
场景 前端传递两个时间参数,开始时间和结束时间,然后从数据库中筛选出某个时间属性在此范围的数据. Mybatis的动态sql的写法. 注: 博客: https://blog.csdn.net/bada ...
- MyBatis 03 动态SQL
MyBatis 03 动态SQL 文章目录 MyBatis 03 动态SQL 一.学习目标 二.动态SQL if 标签2-1 if 标签2-2 where标签2-1 where 标签2-2 choos ...
- SQL关联查询————LEFT JOIN关键字的使用
引言 关联查询一直是非常重要的SQL使用技巧. 在一次查询操作中,使用mybatis进行条件查询,在没有使用 LEFT JOIN 关键字的情况下是这样写的: <!-- 查找成员 -->&l ...
最新文章
- 温度传感器有源电子标签设计浅析
- 【音频处理】Adobe Audition 快捷键设置
- 毕向东Java基础教程(适合初学者入门的Java基础视频)
- 解决 Visual Studio 2019 无法打开wpf设计器问题
- 得到appd url_AppD方法:Java 9支持
- IIS7.0站点/虚拟目录中访问共享
- 计算机图形学——阴影
- linux脚本取前一天时间戳,linux – 为脚本日志条目添加时间戳
- 直方图尖峰python_直方图、密度图、散点图,python数据可视化方法,你要的都在这里...
- android asmack调用MultiUserChat.getHostedRooms方法出现空指针的异常解决方案
- WIN8禁用休眠功能
- 配置深度森林deep forest(2021)环境填坑
- 手机经纬度在线转换工具链接
- 图解谷歌浏览器Chrome的Logo_longware_新浪博客
- CSS3的box-sizing 属性
- 50个查询系列-第13个查询:把“SC”表中“叶平”老师教的课的成绩都更改为此课程的平均成绩;...
- 实验报告怎么写之书写规范
- unity实现角色的移动(用状态机控制动画)
- 关于解决Windows系统许可证即将过期的问题
- crh寄存器_STM32的寄存器控制SDA_IN()/SDA_OUT()
热门文章
- 【Linux系统编程】fork()函数详解
- 【Linux】一步一步学Linux——readonly命令(219)
- c语言使用函数累加由n个a构成的整数之和,c 语言使用函数累加由n个a构成的整数之和...
- 无法对 null 引用执行运行时绑定_你真的懂this吗?聊聊默认绑定,隐式绑定,显示绑定,new绑定...
- atexit注册进程终止处理函数
- 1022 D进制的A+B (20 分)(c语言)
- 二叉树的最大深度—leetcode104
- CentOS安装php mbstring的扩展
- Kalman Filter 学习笔记
- ResNeXt 之 输入数据预处理代码详解