Mybatis xml中配置一对一关系association&一对多关系collection
今天在配置一对一关系映射以及一对多关系映射的时候,把collection中应该使用的ofType配置成了javaType。并且没有及时发现错误,浪费了很多时间去查找此配置问题,特此记一笔。
<resultMap id="DeviceMap" type="com.model.iot.DeviceDto">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="sn" column="sn"/>
<!-- 配置一对一关系 -->
<association property="deviceType" javaType="com.model.iot.DeviceTypeDto" columnPrefix="type_">
<id property="id" column="id"/>
<result property="name" column="name"/>
<!-- 嵌套属性一对多的关系 -->
<collection property="typeExts" ofType="com.model.iot.DeviceTypeExtDto" columnPrefix="ext_">
<id property="id" column="id"/>
<result property="attribute" column="attribute"/>
<result property="dataType" column="dataType"/>
<result property="unit" column="unit"/>
</collection>
</association>
</resultMap>
<select id="deviceList" resultMap="DeviceMap">
SELECT
d.id,
d.NAME,
d.sn,
dt.id AS "type_id",
dt.name AS "type_name",
dte.id AS "type_ext_id",
dte.attribute AS "type_ext_attribute",
dte.dataType AS "type_ext_dataType",
dte.unit AS "type_ext_unit"
FROM
t_device d
LEFT JOIN t_device_type dt ON d.typeId = dt.id
LEFT JOIN t_device_type_ext dte ON dt.id = dte.typeId
</select>
@Data
public class DeviceDto {
private Long id;
private String name;
private String sn;
private DeviceTypeDto deviceType;
}
@Data
public class DeviceTypeDto {
private Long id;
private String name;
private List<DeviceTypeExtDto> typeExts;
}
@Data
public class DeviceTypeExtDto {
private Long id;
private String attribute;
private String dataType;
private String unit;
}
一对一关系中association 使用的是 javaType
::对象对应对象
一对多关系中collection 使用的是ofType
::对象对应集合中的对象
注意columnPrefix的使用方法