mybatis-plus 使用其他mapper中的查询

mybatis-plus 使用其他mapper中的查询

A-mapper.xml中需要引入B-mapper.xml中的映射实现,怎么操作呢?

举个例子,项目有consumer和consumer_conf这2套业务,他们各自拥有controller,mapper,service,pojo;已知consumer和~_conf是1:n的关系,现在查询consumer不但要带出conf中的内容而且需要做分页,而对conf的查询代码已经在consumerConfMapper.xml中写好了,我不想在consumerMapper.xml中再重写一遍,以直接引入全类名的方式实现。例子如下,建议先看最后ConsumerMapper.xml中的代码,再看之前的代码

被引入mapper:ConsumerConfMapper.java

@Mapper
public interface ConsumerConfMapper extends BaseMapper<ConsumerConf> {
    IPage<ConsumerConf> queryConf(@Param(value = "page") IPage page, @Param(value = "id") String id);
}

被引入mapper.xml:ConsumerConfMapper.xml

<?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="org.train.springboot_train.mapper.ConsumerConfMapper">
    <!--org.train.springboot_train.entity.Consumer-->
    <resultMap id="ConsumerConf" type="consumer_conf">
        <result column="consumer_id" property="consumer_id" jdbcType="VARCHAR"/>
        <result column="conf" property="conf" jdbcType="VARCHAR" javaType="string"/>
    </resultMap>
    <select id="queryConf" resultMap="ConsumerConf">
        select consumer_id,conf from consumer_conf where consumer_id = #{id}
    </select>
</mapper>

ConsumerMapper.xml

<resultMap id="ContainItem" type="consumer">
    <result column="id" property="id" javaType="string" jdbcType="VARCHAR"/>
    <result column="name" property="name" javaType="string" jdbcType="VARCHAR"/>
    <result column="age" property="age" javaType="integer" jdbcType="INTEGER"/>
    <result column="sex" property="sex" jdbcType="BIT"/>
    <collection property="consumerConfs"
                column="id"
                <!--这里直接引入全类名即可-->
                select="org.train.springboot_train.mapper.ConsumerConfMapper.queryConf"
                ofType="consumer_conf">
    </collection>
    
    <select id="findContainItemById" resultMap="ContainItem">
        select <include refid="all_fields"/> from consumer
    </select>
</resultMap>

⚠️ 注意
在 MyBatis 的 mapper.xml 文件中不能直接使用由 BaseMapper 接口提供的方法名(如 selectById)作为 <association> 或 <collection> 标签的 select 属性的值

posted @ 2024-08-14 20:46  勤匠  阅读(61)  评论(0)    收藏  举报