MyBatis实践之动态SQL及关联查询

序言

mybatis,大家都知道,半自动的orm框架,原来叫ibatis,后来好像是10年apache软件基金组织把它托管给了goole code,就重新命名了mybatis,功能相对以前更强大了。它相对全自动的持久层框架hibernate,更加灵活,更轻量级,这点我还是深有体会的。

mybatis的一个强大特性之一就是动态sql能力了,能省去我们很多串联判断拼接sql的痛苦,根据项目而定,在一定的场合下使用,能大大减少程序的代码量和复杂程度,不过还是不是过度太过复杂的使用,以免不利于后期的维护和扩展。

动态sql

动态sql提供了对sql语句的灵活操作,通过表达式进行判断,对sql进行拼接/组装.

if

对查询条件进行判断,如果输入参数不为空才进行查询条件的拼接.

mapper

<code class=" hljs vbnet"><select id="selectuser" resulttype="com.fq.domain.user" parametertype="com.fq.domain.user">
select * from user
and id = #{id}
and name = #{name}
and password = #{password}
</select></code>

会自动处理第一个and(mybatis还提供了自定义行为的元素, 详细可参考mybatis文档).

userdao

<code class="hljs vbnet"><code class="hljs php">list<user> selectuser(user user) throws exception;</user></code></code>

client

<code class="hljs vbnet"><code class="hljs php"><code class="hljs java">@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);
}</code></code></code>

由于id与name为null, 因此这两个条件不会拼接在sql中,这一点可以调试时日志中看出.

choose/when/otherwise

有些时候,我们并不想用到所有的条件语句,而只想从中选择一二.针对这种情况,mybatis提供了元素,他有点像java中的switch.

<code class=" hljs vbnet"><code class=" hljs php"><code class=" hljs java"><code class=" hljs vbnet"><select id="selectuser" resulttype="com.fq.domain.user" parametertype="com.fq.domain.user">
select * from user
and id = #{id}
and name = #{name}
and password = #{password}
</select></code></code></code></code>

set

用于动态更新语句的解决方案为,set元素可以被用于动态包含需要更新的列, 而舍去其他的.

<code class="hljs vbnet"><code class="hljs php"><code class="hljs java"><code class="hljs vbnet"><code class="hljs applescript"><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></code></code></code></code></code>

foreach

使用foreach可以实现向sql中传递数组或list:

传入list

查询多个id的用户信息, 可以由下面两种sql实现:

<code class="hljs vbnet"><code class="hljs php"><code class="hljs java"><code class="hljs vbnet"><code class="hljs applescript"><code class="hljs sql">select * from user where (id = ? or id = ? or id = ?);
select * from user where id in (?, ?, ?, ?);</code></code></code></code></code></code>

因此其foreach的定义也有如下两种方案:

<code class=" hljs vbnet"><code class=" hljs php"><code class=" hljs java"><code class=" hljs vbnet"><code class=" hljs applescript"><code class=" hljs sql"><code class=" hljs cs"><select id="selectuser" parametertype="java.util.list" resulttype="com.fq.domain.user">
select *
from user
id = #{id}
</select></code></code></code></code></code></code></code>
<code class=" hljs vbnet"><code class=" hljs php"><code class=" hljs java"><code class=" hljs vbnet"><code class=" hljs applescript"><code class=" hljs sql"><code class=" hljs cs"><code class=" hljs cs"><select id="selectuser" parametertype="java.util.list" resulttype="com.fq.domain.user">
select *
from user
#{id}
</select></code></code></code></code></code></code></code></code>

元素 描述

collection sql解析的参数名
index 循环下标
item 单个元素的名
open 循环开始输出
close 循环结束输出
separator 中间分隔输出

传递list作为parametertype时,sql解析参数名固定为list.

userdao

<code class="hljs vbnet"><code class="hljs php"><code class="hljs java"><code class="hljs vbnet"><code class="hljs applescript"><code class="hljs sql"><code class="hljs cs"><code class="hljs cs"><code class="hljs mathematica">list<user> selectuser(list<integer> ids) throws exception;</integer></user></code></code></code></code></code></code></code></code></code>

批量插入用户案例

mapper

<code class="hljs vbnet"><code class="hljs php"><code class="hljs java"><code class="hljs vbnet"><code class="hljs applescript"><code class="hljs sql"><code class="hljs cs"><code class="hljs cs"><code class="hljs mathematica"><code class="hljs xml"><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></code></code></code></code></code></code></code></code></code></code>

userdao

<code class="hljs vbnet"><code class="hljs php"><code class="hljs java"><code class="hljs vbnet"><code class="hljs applescript"><code class="hljs sql"><code class="hljs cs"><code class="hljs cs"><code class="hljs mathematica"><code class="hljs xml"><code class="hljs java">void insertuserlist(list<user> users) throws exception;</user></code></code></code></code></code></code></code></code></code></code></code>

client

<code class="hljs vbnet"><code class="hljs php"><code class="hljs java"><code class="hljs vbnet"><code class="hljs applescript"><code class="hljs sql"><code class="hljs cs"><code class="hljs cs"><code class="hljs mathematica"><code class="hljs xml"><code class="hljs java"><code class="hljs java">@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")));
}</code></code></code></code></code></code></code></code></code></code></code></code>

传入数组

mapper

<code class=" hljs vbnet"><code class=" hljs php"><code class=" hljs java"><code class=" hljs vbnet"><code class=" hljs applescript"><code class=" hljs sql"><code class=" hljs cs"><code class=" hljs cs"><code class=" hljs mathematica"><code class=" hljs xml"><code class=" hljs java"><code class=" hljs java"><code class=" hljs cs"><select id="selectuser" parametertype="object[]" resulttype="com.fq.domain.user">
select *
from user
#{id}
</select></code></code></code></code></code></code></code></code></code></code></code></code></code>

与list类似,传递数组作为parametertype时,sql解析参数名固定为array.

userdao

<code class="hljs vbnet"><code class="hljs php"><code class="hljs java"><code class="hljs vbnet"><code class="hljs applescript"><code class="hljs sql"><code class="hljs cs"><code class="hljs cs"><code class="hljs mathematica"><code class="hljs xml"><code class="hljs java"><code class="hljs java"><code class="hljs cs"><code class="hljs mathematica">list<user> selectuser(integer[] ids) throws exception;</user></code></code></code></code></code></code></code></code></code></code></code></code></code></code>

sql片段

可以将一段公共的sql语句抽取出来, 作为一个sql片段, 供其他sql调用:

<code class=" hljs vbnet"><code class=" hljs php"><code class=" hljs java"><code class=" hljs vbnet"><code class=" hljs applescript"><code class=" hljs sql"><code class=" hljs cs"><code class=" hljs cs"><code class=" hljs mathematica"><code class=" hljs xml"><code class=" hljs java"><code class=" hljs java"><code class=" hljs cs"><code class=" hljs mathematica"><code class=" hljs vbnet"><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
</select></code></code></code></code></code></code></code></code></code></code></code></code></code></code></code>

经验:最好基于单表定义sql片段,而且在sql片段中不要包含/之类的标签,这样可以保证sql片段重用度更高.

关联查询

数据模型分析思路

每张表的数据内容:分模块对每张表记录的内容进行熟悉,相当于学习系统需求/功能. 每张表重要的字段:非空字段/外键字段等. 表与表之间的数据库级别关系: 外键关系. 表与表之间的业务关系:建立在某个业务的基础上去分析.

订单/商品数据模型

表内容

user: 购买商品的用户信息 order: 用户创建的订单 orderdetail: 订单详细(购买商品信息) item: 商品信息 表与表之间的业务关系:

user/order:
user -> order: 一对多 order -> user: 一对一 order/orderdetail:
order -> orderdetail:一对多 orderdetail -> order:一对一 orderdetail/item:
orderdetail -> item:一对一 item -> orderdetail:一对多

‘一对一’查询

需求: 查询订单信息,关联查询(创建订单的)用户信息.

由以上分析可知主查询为order表,而order -> user关系为一对一, 因此使用resultmap将查询结果的订单信息映射到order中,将用户信息映射到order中的user属性.

po: 改造user

<code class="hljs vbnet"><code class="hljs php"><code class="hljs java"><code class="hljs vbnet"><code class="hljs applescript"><code class="hljs sql"><code class="hljs cs"><code class="hljs cs"><code class="hljs mathematica"><code class="hljs xml"><code class="hljs java"><code class="hljs java"><code class="hljs cs"><code class="hljs mathematica"><code class="hljs vbnet"><code class="hljs java">public class user implements serializable {
private integer id;
private string username;
private date birthday;
private integer sex;
private string address;
// ..
}</code></code></code></code></code></code></code></code></code></code></code></code></code></code></code></code>

po: 新增order, 将user组合到order中:

<code class="hljs vbnet"><code class="hljs php"><code class="hljs java"><code class="hljs vbnet"><code class="hljs applescript"><code class="hljs sql"><code class="hljs cs"><code class="hljs cs"><code class="hljs mathematica"><code class="hljs xml"><code class="hljs java"><code class="hljs java"><code class="hljs cs"><code class="hljs mathematica"><code class="hljs vbnet"><code class="hljs java"><code class="hljs java">public class order implements serializable {
private integer id;
private integer userid;
private string number;
private date createtime;
private string note;
private user user;
// ...
}</code></code></code></code></code></code></code></code></code></code></code></code></code></code></code></code></code>

mapper

<code class=" hljs vbnet"><code class=" hljs php"><code class=" hljs java"><code class=" hljs vbnet"><code class=" hljs applescript"><code class=" hljs sql"><code class=" hljs cs"><code class=" hljs cs"><code class=" hljs mathematica"><code class=" hljs xml"><code class=" hljs java"><code class=" hljs java"><code class=" hljs cs"><code class=" hljs mathematica"><code class=" hljs vbnet"><code class=" hljs java"><code class=" hljs java"><code class=" hljs xml"><!--{cke_protected}{c}%3c!%2d%2d%3fxml%20version%3d%221.0%22%20encoding%3d%22utf-8%22%20%3f%2d%2d%3e-->
<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">
</result></result></result></result></id></association>
</result></result></result></result></id></resultmap>
<select id="selectorderwithuser" resultmap="order_user_map">
select
`order`.*,
username,
birthday,
sex,
address
from `order`, user
where `order`.user_id = user.id and `order`.id = #{0};
</select>
</cache></mapper></code></code></code></code></code></code></code></code></code></code></code></code></code></code></code></code></code></code>
association: 映射关联查询的单条记录(将关联查询信息映射到po对象属性).

orderdao

<code class="hljs vbnet"><code class="hljs php"><code class="hljs java"><code class="hljs vbnet"><code class="hljs applescript"><code class="hljs sql"><code class="hljs cs"><code class="hljs cs"><code class="hljs mathematica"><code class="hljs xml"><code class="hljs java"><code class="hljs java"><code class="hljs cs"><code class="hljs mathematica"><code class="hljs vbnet"><code class="hljs java"><code class="hljs java"><code class="hljs xml"><code class="hljs cs">public interface orderdao {
order selectorderwithuser(integer id) throws exception;
}</code></code></code></code></code></code></code></code></code></code></code></code></code></code></code></code></code></code></code>

client

<code class="hljs vbnet"><code class="hljs php"><code class="hljs java"><code class="hljs vbnet"><code class="hljs applescript"><code class="hljs sql"><code class="hljs cs"><code class="hljs cs"><code class="hljs mathematica"><code class="hljs xml"><code class="hljs java"><code class="hljs java"><code class="hljs cs"><code class="hljs mathematica"><code class="hljs vbnet"><code class="hljs java"><code class="hljs java"><code class="hljs xml"><code class="hljs cs"><code class="hljs java">@runwith(springjunit4classrunner.class)
@contextconfiguration(locations = "classpath:spring/applicationcontext.xml")
public class orderdaoclient {
@autowired
private orderdao dao;
@test
public void client() throws exception {
order order = dao.selectorderwithuser(3);
system.out.println(order);
}
}</code></code></code></code></code></code></code></code></code></code></code></code></code></code></code></code></code></code></code></code>

‘一对多’查询

需求: 查询订单及订单明细的信息(一对多).

po: 定义orderdetail,并在order中添加list orderdetails订单明细属性:

<code class="hljs java">public class orderdetail implements serializable {
private integer id;
private integer orderid;
private integer itemid;
private integer itemnumber;
// ...
}</code>

mapper

<code class=" hljs java"><code class=" hljs vbnet"><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">
</result></result></result></id></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_id
from `order`, user, orderdetail
where `order`.user_id = user.id and `order`.id = orderdetail.order_id and `order`.id = #{0};
</select></code></code>

元素 描述

property 指定关联查询的结果集存储到的属性

oftype 指定关联查询结果集中的对象类型orderdao

<code class="hljs java"><code class="hljs vbnet"><code class="hljs mathematica">order selectorderwithdetail(integer id) throws exception;</code></code></code>

‘多对多’查询

需求: 查询用户及用户购买商品信息.

由于user表与item表没有直接关联,因此只能通过order表与orderdetail表进行关联.

思路:

1) 将用户信息映射到user中.
2) 在user中添加list订单列表属性,将用户创建的订单映射到orders.
3) 在order中添加list订单明细列表属性,将订单的明细映射到orderdetails.
4) 在orderdetail中添加item属性,将订单明细所对应的商品映射到item.

po: item

<code class="hljs java"><code class="hljs vbnet"><code class="hljs mathematica"><code class="hljs cs">public class item {
private integer id;
private string name;
private float price;
private string detail;
private string pic;
private date createtime;
//...
}</code></code></code></code>

mapper

<code class=" hljs java"><code class=" hljs vbnet"><code class=" hljs mathematica"><code class=" hljs cs"><code class=" hljs applescript"><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">
</result></result></result></result></result></id></association>
</result></result></result></id></collection>
</result></result></result></result></id></collection>
</result></result></result></result></id></resultmap>
<select id="selectuseritem" resultmap="user_item_map">
select
user.*,
`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_pic
from user, item, `order`, orderdetail
where `order`.user_id = user.id and orderdetail.order_id = `order`.id and orderdetail.item_id = item.id ;
</select></code></code></code></code></code>

orderdao

<code class="hljs java"><code class="hljs vbnet">
<code class="hljs mathematica">
<code class="hljs cs">
<code class="hljs applescript">
<code class="hljs php">list<user> selectuseritem() throws exception;</user>
</code></code></code></code></code></code>

resultmap小结:

使用和可以完成一对一和一对多的高级映射.

association: 将关联查询信息映射到一个po对象中. collection: 将关联查询信息映射到一个集合中.

延迟加载

关联查询时,使用mybatis 延迟加载 特性可有效减轻数据库压力.首次查询只查询主表信息,等需要时再去查询关联表信息.的/具备延迟加载功能.

需求: 查询订单信息并关联查询用户信息.

延迟加载开关

在mybatis核心配置文件(mybatis-configuration.xml)中配置:

1) lazyloadingenabled : 设置是否懒加载.默认false,则所有关联查询都会被初始化加载.

2) aggressivelazyloading : 设置是否积极加载. 默认true,所有关联属性被初始化加载.

settings配置:

<code class=" hljs java">
<code class=" hljs vbnet"><code class=" hljs mathematica">
<code class=" hljs cs"><code class=" hljs applescript"><code class=" hljs php">
<code class=" hljs xml"><settings>
<setting name="cacheenabled" value="true">
<setting name="lazyloadingenabled" value="true">
<setting name="aggressivelazyloading" value="false">
</setting></setting></setting></settings></code></code></code></code></code></code></code>

mapper

只查询订单信息

<code class=" hljs java"><code class=" hljs vbnet"><code class=" hljs mathematica"><code class=" hljs cs"><code class=" hljs applescript"><code class=" hljs php"><code class=" hljs xml"><code class=" hljs applescript"><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">
</association></result></result></result></result></id></resultmap>
<select id="selectorderwithuser" resultmap="order_user_map">
select *
from `order`;
</select></code></code></code></code></code></code></code></code>

元素 描述

select 指定关联查询statement为com.fq.mybatis.userdao.selectuserbyid.

column 指定关联查询时将users_id值传入selectuserbyid.关联查询用户信息(namespace为com.fq.mybatis.userdao)

<code class=" hljs java"><code class=" hljs vbnet"><code class=" hljs mathematica"><code class=" hljs cs"><code class=" hljs applescript"><code class=" hljs php"><code class=" hljs xml"><code class=" hljs applescript"><code class=" hljs vbnet"><select id="selectuserbyid" parametertype="java.lang.integer" resulttype="com.fq.domain.user">
select *
from user
where id = #{id};
</select></code></code></code></code></code></code></code></code></code>

将上面查询到的订单信息中的user_id传入selectuserbyid来关联查询用户信息.

orderdao(同前)

<code class="hljs java">
<code class="hljs vbnet">
<code class="hljs mathematica">
<code class="hljs cs">
<code class="hljs applescript">
<code class="hljs php">
<code class="hljs xml">
<code class="hljs applescript">
<code class="hljs vbnet">
<code class="hljs mathematica">list<order> selectorderwithuser() throws exception;</order>
</code>
</code></code></code></code></code></code></code></code></code>

client

<code class="hljs java"><code class="hljs vbnet"><code class="hljs mathematica"><code class="hljs cs"><code class="hljs applescript"><code class="hljs php"><code class="hljs xml"><code class="hljs applescript"><code class="hljs vbnet"><code class="hljs mathematica"><code class="hljs java">@runwith(springjunit4classrunner.class)
@contextconfiguration(locations = "classpath:spring/applicationcontext.xml")
public class orderdaoclient {
@autowired
private orderdao dao;
@test
public void client() throws exception {
list<order> orders = dao.selectorderwithuser();
for (order order : orders) {
system.out.println(order.getuser());
}
}
}</order></code></code></code></code></code></code></code></code></code></code></code>

debug上面client, 观察log信息,会发现只有当确实需要user信息时才会调用selectuserbyid.

以上所述是www.887551.com给大家介绍的mybatis实践之动态sql及关联查询,希望对大家以上帮助!

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐