创建自定义映射规则
<select id="selectArtist" resultMap="test">select * from artist
</select>
在SQL语句标签中将resultType修改为resultMap,即自定义映射的id。
编写自定义映射规则:
<resultMap id="test" type="com.test.artist">
<result column="aID" property="aID_java"/>
</resultMap>
resultMap标签:id用以连接select标签,type代替了select标签中的resultType属性。
result标签:column代表数据库中的字段名,property代表赋值给的实体类成员变量名。
实现多表查询
1.一对多查询:
@Data
public class Teacher {int tid;String name;List<Student> studentList;
}
<select id="getTeacherByTid" resultMap="asTeacher">
select *, teacher.name as tname from student
inner join teach on student.sid = teach.sid
inner join teacher on teach.tid = teacher.tid where teach.tid = #{tid}
</select><resultMap id="asTeacher" type="Teacher"><id column="tid" property="tid"/><result column="tname" property="name"/><collection property="studentList" ofType="Student"><id property="sid" column="sid"/><result column="name" property="name"/><result column="sex" property="sex"/></collection>
</resultMap>
result.id:表示自定义映射的唯一标识,不能重复。
collection标签:property表示集合的成员变量名称,ofType表示集合数据泛型(为一个类)。
在collection标签中继续写子查询结果列表。
2.多对一查询:
<resultMap id="test2" type="Student"><id column="sid" property="sid"/><result column="name" property="name"/><result column="sex" property="sex"/><association property="teacher" javaType="Teacher"><id column="tid" property="tid"/><result column="tname" property="name"/></association>
</resultMap>
<select id="selectStudent" resultMap="test2">select *, teacher.name as tname from student left join teach on student.sid = teach.sidleft join teacher on teach.tid = teacher.tid
</select>
association标签:property表示实体类的成员变量名称,ofType表示变量类型(为一个类)。
在association标签中继续写子查询结果列表。