mybatis中association和collection

1、整體概述

JavaType和ofType都是用來指定對象類型的,但是JavaType是用來指定pojo中屬性的類型,而ofType指定的是映射到list集合屬性中pojo的類型。

 

2、association(一對一關聯)

 

DO


public class BuildingMaintenanceDO  {
    private String id;
    private Double problemNum;
    private Double fireScore;

}

DTO

public class BuildingMaintenanceDto extends BuildingMaintenanceDO {

    private List<FileDto> fileDto;

}

mapper.xml

 

 <!--1對1-->
    <resultMap id="getMaintenanceDtoListMapOneToOne"
               type="com.atpdc.springboot.dto.BuildingMaintenanceDto" autoMapping="true">
        <!-- BuildingDO 相關信息,必須有id纔行-->
        <id column="id" jdbcType="VARCHAR" property="id"/>
        <!--關聯的參數 1對1  fileDto-->
        <association columnPrefix="sf_" property="fileDto" javaType="com.atpdc.springboot.dto.FileDto">
            <id column="id" jdbcType="VARCHAR" property="id"/>
            <id column="file_name_origin" jdbcType="VARCHAR" property="fileNameOrigin"/>
            <id column="http_path" jdbcType="VARCHAR" property="httpPath"/>
        </association>
    </resultMap>


 <select id="getMaintenanceById" resultMap="getMaintenanceDtoListMapOneToOne">
        select
        fbm.id,
        fbm.building_id,
        fbm.building_name,
        fbm.maintenance_date,
        fbm.problem_num,
        fbm.fire_score,
        fbm.security_score,
        fbm.platform_score,
        fbm.detail,
        fbm.file_id,
        fbm.create_user_id,
        fbm.modified_user_id,
        fbm.gmt_modified,
        fbm.gmt_create,
        fbm.is_deleted,
        sf.id as sf_id,
        sf.file_name_origin as sf_file_name_origin,
        sf.http_path as sf_http_path
        from fc_building_maintenance fbm
        left join sys_file sf on FIND_IN_SET( sf.id,fbm.file_id)
        where fbm.id = #{maintenanceId}
    </select>

 

 

 

3、collection(一對多關聯)

JavaType和ofType都是用來指定對象類型的,但是JavaType是用來指定pojo中屬性的類型,而ofType指定的是映射到list集合屬性中pojo的類型。
 
mapper.xml
<select id="getMaintenanceById" resultMap="getMaintenanceDtoListMapOneToMany">
    select
    fbm.*,
    sf.id as sf_id,
    sf.file_name_origin as sf_file_name_origin,
    sf.http_path as sf_http_path
    from fc_building_maintenance fbm
    left join sys_file sf on FIND_IN_SET( sf.id,fbm.file_id)
    where fbm.id = #{maintenanceId}
</select>

<!--1對 多,必須使用ofType-->
<resultMap id="getMaintenanceDtoListMapOneToMany"
           type="com.atpdc.springboot.dto.BuildingMaintenanceDto" autoMapping="true">
    <!-- BuildingDO 相關信息,必須有id纔行-->
    <id column="id" jdbcType="VARCHAR" property="id"/>
    <!--關聯的參數 fileDto-->
    <collection columnPrefix="sf_" property="fileDto" ofType="com.atpdc.springboot.dto.FileDto">
        <id column="id" jdbcType="VARCHAR" property="id"/>
        <id column="file_name_origin" jdbcType="VARCHAR" property="fileNameOrigin"/>
        <id column="http_path" jdbcType="VARCHAR" property="httpPath"/>
    </collection>
</resultMap>
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章