MyBatis跨xml嵌套

背景:多个xml需要套起来复用,写在一个xml文件或者单独写个base文件,用于复用。

步骤:

  1. 新建base文件,注意命名空间
  2. 引用到需要的xml中

实现:

  • base文件,注意命名空间,要被扫描到
<?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.XXX.infra.mapper.ExceptionInfoBaseSqlMapper">
    <sql id="smartMeterCol">
        lsm.process_status processStatus,
        lsm.device_number deviceNumber
    </sql>
    <sql id="smartMeterWhere">
        <where>
            <if test=" area!=null ">
                and lsm.area = #{area}
            </if>
        </where>
    </sql>
</mapper>
  • 引用,include中的引用必须是全命名空间
<?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.lzsh.infra.mapper.SummaryWarnMapper">

	<select id="list">
        select * from (
            select
              <include refid="com.XXX.infra.mapper.ExceptionInfoBaseSqlMapper.smartMeterCol"/>
            from table
              <include refid="com.XXX.infra.mapper.ExceptionInfoBaseSqlMapper.smartMeterWhere"/>  
        ) a order by a.alertTime desc
    </select>
</mapper>

MyBatis是一个开源的持久层框架,它提供了丰富的查询功能,其中包括嵌套查询。嵌套查询是指在一个查询语句中嵌套执行另一个查询语句,以获取更复杂的结果。 MyBatis提供了两种方式来实现嵌套查询: 1. 使用嵌套结果映射(Nested Result Maps):通过定义多个结果映射,将嵌套查询的结果映射到对应的对象中。在主查询中使用`association`或`collection`标签来引用嵌套查询的结果映射。这种方式适用于一对一或一对多的关联关系。 2. 使用嵌套查询语句(Nested Selects):在主查询中使用`select`标签来执行嵌套查询语句,并将查询结果作为参数传递给主查询。这种方式适用于需要在嵌套查询中使用动态参数的情况。 下面是一个示例,演示了如何使用MyBatis进行嵌套查询: ```xml <!-- 定义嵌套查询的结果映射 --> <resultMap id="userResultMap" type="User"> <id property="id" column="id" /> <result property="username" column="username" /> <result property="email" column="email" /> <!-- 嵌套查询的结果映射 --> <association property="role" resultMap="roleResultMap" /> </resultMap> <!-- 定义嵌套查询的语句 --> <select id="getUserWithRole" resultMap="userResultMap"> SELECT u.id, u.username, u.email, r.id AS role_id, r.name AS role_name FROM users u INNER JOIN roles r ON u.role_id = r.id WHERE u.id = #{id} </select> ``` 在上面的示例中,`getUserWithRole`是主查询语句,它通过`association`标签引用了名为`roleResultMap`的嵌套查询结果映射。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值