像是下面这样的,如果真要一个个地去把 reulst 子标签写出来,有点不太现实,还好 mybatis 提供了 autoMapping,可以作用在 association 和 resultMap 标签上:
<resultMap id="mapOfQueryMyself" type="Student" autoMapping="true">
<association property="college" columnPrefix="c_" javaType="College">
<id property="cno" column="cno"/>
<result property="name" column="name"/>
<result property="intro" column="intro"/>
</association>
<association property="profession" columnPrefix="p_" javaType="Profession" autoMapping="true">
<id property="pno" column="pno"/>
<result property="name" column="name"/>
<result property="type" column="type"/>
<result property="eduSys" column="edu_sys"/>
<result property="degree" column="degree"/>
<result property="code" column="code"/>
</association>
<association property="grade" columnPrefix="g_" javaType="Grade">
<id property="gno" column="gno"/>
<result property="name" column="name"/>
<result property="layer" column="layer"/>
<result property="grade" column="grade"/>
</association>
</resultMap>
用 autoMapping 之前,联合查询中,一对一关系需要给字段别名,最好用一种格式,比如 c_xxx
,在 association 中添加 columnPrefix,然后再开启 autoMapping 就可以完美匹配查询过后的字段:
<resultMap id="mapOfQueryMyself" type="Student" autoMapping="true">
<association property="college" columnPrefix="c_" javaType="College" autoMapping="true"/>
<association property="profession" columnPrefix="p_" javaType="Profession" autoMapping="true"/>
<association property="grade" columnPrefix="g_" javaType="Grade" autoMapping="true"/>
</resultMap>
<select id="queryMyself" resultMap="mapOfQueryMyself">
SELECT s.*,
c.cno c_cno,
c.name c_name,
p.pno p_pno,
p.name p_name,
p.type p_type,
p.edu_sys p_edu_sys,
p.degree p_degree,
p.code p_code,
g.gno g_gno,
g.name g_name,
g.layer g_layer,
g.grade g_grade
FROM `students` as s
JOIN `colleges` as c on c.cno = s.college_id
JOIN `grades` as g on g.gno = s.grade_id
JOIN `professions` as p on p.pno = s.profession_id
WHERE s.sno = 1;
</select>
标签:name,映射,一对一,grade,autoMapping,Mybatis,cno,id
From: https://www.cnblogs.com/Enziandom/p/16990630.html