MyBatis 实践 -动态SQL/关联查询

简介: MyBatis 实践标签: Java与存储动态SQL动态SQL提供了对SQL语句的灵活操作,通过表达式进行判断,对SQL进行拼接/组装.

MyBatis 实践

标签: 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>
AI 代码解读

<where/>会自动处理第一个AND(MyBatis还提供了自定义<where/>行为的<trim/>元素, 详细可参考MyBatis文档).

  • UserDAO
List<User> selectUser(User user) throws Exception;
AI 代码解读
  • 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);
}
AI 代码解读

由于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>
AI 代码解读

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>
AI 代码解读

foreach

使用foreach可以实现向SQL中传递数组List:

传入List

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

SELECT * FROM user WHERE (id = ? OR id = ? OR id = ?);
SELECT * FROM user WHERE id IN (?, ?, ?, ?);
AI 代码解读

因此其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>
AI 代码解读
<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>
AI 代码解读
元素 描述
collection SQL解析的参数名
index 循环下标
item 单个元素的名
open 循环开始输出
close 循环结束输出
separator 中间分隔输出

传递List作为parameterType时,SQL解析参数名固定为list.

  • UserDAO
List<User> selectUser(List<Integer> ids) throws Exception;
AI 代码解读

批量插入用户案例

  • 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>
AI 代码解读
  • UserDAO
void insertUserList(List<User> users) throws Exception;
AI 代码解读
  • 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")));
}
AI 代码解读

传入数组

  • 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>
AI 代码解读

List类似,传递数组作为parameterType时,SQL解析参数名固定为array.

  • UserDAO
List<User> selectUser(Integer[] ids) throws Exception;
AI 代码解读

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>
AI 代码解读

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


关联查询

  • 数据模型分析思路

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

    • 表内容
      • user: 购买商品的用户信息
      • order: 用户创建的订单
      • orderdetail: 订单详细(购买商品信息)
      • item: 商品信息
    • 表与表之间的业务关系:
      1. user/order:
        • user -> order: 一对多
        • order -> user: 一对一
      2. order/orderdetail:
        • order -> orderdetail:一对多
        • orderdetail -> order:一对一
      3. orderdetail/item:
        • orderdetail -> item:一对一
        • item -> orderdetail:一对多

‘一对一’查询

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

由以上分析可知主查询为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;

    // ...
}
AI 代码解读
  • 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;

    // ...
}
AI 代码解读
  • 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,
        address
        FROM `order`, user
        WHERE `order`.user_id = user.id AND `order`.id = #{0};
    </select>

</mapper>
AI 代码解读

association: 映射关联查询的单条记录(将关联查询信息映射到PO对象属性).

  • OrderDAO
public interface OrderDAO {
    Order selectOrderWithUser(Integer id) throws Exception;
}
AI 代码解读
  • Client
@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);
    }
}
AI 代码解读

‘一对多’查询

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

  • PO: 定义OrderDetail,并在Order中添加List<OrderDetail> orderDetails订单明细属性:
public class OrderDetail implements Serializable {

    private Integer id;

    private Integer orderId;

    private Integer itemId;

    private Integer itemNumber;

    // ...
}
AI 代码解读
  • 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_id
    FROM `order`, user, orderdetail
    WHERE `order`.user_id = user.id AND `order`.id = orderdetail.order_id AND `order`.id = #{0};
</select>
AI 代码解读
元素 描述
property 指定关联查询的结果集存储到的属性
ofType 指定关联查询结果集中的对象类型
  • OrderDAO
Order selectOrderWithDetail(Integer id) throws Exception;
AI 代码解读

‘多对多’查询

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

由于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;

    //...
}
AI 代码解读
  • 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">
    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>
AI 代码解读
  • OrderDAO
List<User> selectUserItem() throws Exception;
AI 代码解读

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>
AI 代码解读

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>
AI 代码解读
元素 描述
select 指定关联查询Statementcom.fq.mybatis.UserDAO.selectUserById.
column 指定关联查询时将users_id值传入selectUserById.
  • 关联查询用户信息(namespacecom.fq.mybatis.UserDAO)
<select id="selectUserById" parameterType="java.lang.Integer" resultType="com.fq.domain.User">
    SELECT *
    FROM user
    WHERE id = #{id};
</select>
AI 代码解读

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

  • OrderDAO(同前)
List<Order> selectOrderWithUser() throws Exception;
AI 代码解读
  • Client
@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());
        }
    }
}
AI 代码解读

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


目录
打赏
0
0
0
0
12
分享
相关文章
SQL查询太慢?实战讲解YashanDB SQL调优思路
本文是Meetup第十期“调优实战专场”的第二篇技术文章,上一篇《高效查询秘诀,解码YashanDB优化器分组查询优化手段》中,我们揭秘了YashanDB分组查询优化秘诀,本文将通过一个案例,助你快速上手YashanDB慢日志功能,精准定位“慢SQL”后进行优化。
玩转大数据:从零开始掌握SQL查询基础
玩转大数据:从零开始掌握SQL查询基础
72 35
如何在Django中正确使用参数化查询或ORM来避免SQL注入漏洞?
如何在Django中正确使用参数化查询或ORM来避免SQL注入漏洞?
177 77
利用 PolarDB PG 版向量化引擎,加速复杂 SQL 查询!完成任务领发财新年抱枕!
利用 PolarDB PG 版向量化引擎,加速复杂 SQL 查询!完成任务领发财新年抱枕!
云原生数据仓库AnalyticDB PostgreSQL同一个SQL可以实现向量索引、全文索引GIN、普通索引BTREE混合查询,简化业务实现逻辑、提升查询性能
本文档介绍了如何在AnalyticDB for PostgreSQL中创建表、向量索引及混合检索的实现步骤。主要内容包括:创建`articles`表并设置向量存储格式,创建ANN向量索引,为表增加`username`和`time`列,建立BTREE索引和GIN全文检索索引,并展示了查询结果。参考文档提供了详细的SQL语句和配置说明。
30 1
【YashanDB知识库】字段加上索引后,SQL查询不到结果
【YashanDB知识库】字段加上索引后,SQL查询不到结果
|
10天前
|
六、MyBatis特殊的SQL:模糊查询、动态设置表名、校验名称唯一性
六、MyBatis特殊的SQL:模糊查询、动态设置表名、校验名称唯一性
24 0
|
2月前
|
Java使用sql查询mongodb
通过MongoDB Atlas Data Lake或Apache Drill,可以在Java中使用SQL语法查询MongoDB数据。这两种方法都需要适当的配置和依赖库的支持。希望本文提供的示例和说明能够帮助开发者实现这一目标。
63 17
如何在 Oracle 中配置和使用 SQL Profiles 来优化查询性能?
在 Oracle 数据库中,SQL Profiles 是优化查询性能的工具,通过提供额外统计信息帮助生成更有效的执行计划。配置和使用步骤包括:1. 启用自动 SQL 调优;2. 手动创建 SQL Profile,涉及收集、执行调优任务、查看报告及应用建议;3. 验证效果;4. 使用 `DBA_SQL_PROFILES` 视图管理 Profile。
SQL做数据分析的困境,查询语言无法回答的真相
SQL 在简单数据分析任务中表现良好,但面对复杂需求时显得力不从心。例如,统计新用户第二天的留存率或连续活跃用户的计算,SQL 需要嵌套子查询和复杂关联,代码冗长难懂。Python 虽更灵活,但仍需变通思路,复杂度较高。相比之下,SPL(Structured Process Language)语法简洁、支持有序计算和分组子集保留,具备强大的交互性和调试功能,适合处理复杂的深度数据分析任务。SPL 已开源免费,是数据分析师的更好选择。
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等