mybatis plus在Mapper.xml中嵌套查詢的方式


有兩種,第一種是子查詢,第二種是連接查詢
第一種,額外建立一個子查詢,並定義resultMap,手動映射返回id、屬性、集合

<?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.huawei.energytools.mapper.ProductMapper">
    <resultMap id="productResult" type="Product">
        <id column="id" property="id"/>
        <result column="project_id" property="projectId"/>
        <result column="name" property="name"/>
        <result column="count" property="count"/>
        <result column="brand" property="brand"/>
        <result column="custom" property="custom"/>
        <result column="required_shipment_time" property="requiredShipmentTime"/>
        <collection column="id" property="drawings" ofType="FileInfo" select="selectDrawings"/>
    </resultMap>

    <select id="selectDrawings" resultType="FileInfo">
        select *
        from file
        where product_id = #{id}
    </select>

    <select id="selectNewList" resultMap="productResult">
        select *
        from product p 
        where p.project_id = #{projectId}
    </select>
</mapper>

第二種,通過連接查詢,需要注意的是兩張表的主鍵相同的情況下需要在查詢中建立別名,並在resultMap中建立映射

<?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.huawei.energytools.mapper.ProductMapper">

    <resultMap id="productResult" type="Product">
        <id column="id" property="id"/>
        <result column="project_id" property="projectId"/>
        <result column="name" property="name"/>
        <result column="count" property="count"/>
        <result column="brand" property="brand"/>
        <result column="custom" property="custom"/>
        <result column="required_shipment_time" property="requiredShipmentTime"/>
        <collection property="drawings" ofType="FileInfo">
            <result column="fileId" property="id" />
        </collection>
    </resultMap>

    <select id="selectNewList" resultMap="productResult">
        select p.*,
               f.id fileId
        from product p left join file f on p.id = f.product_id
    </select>
</mapper>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM