mybatis 连表查询mapper格式
实体类
public class StudentEntity {
private int id;
private String name;
private TeacherEntity teacherEntity; //属性是关联表实体类
//构造(有参,无参),set ,get ,toSting
}
public class TeacherEntity {
private int id;
private String name;
//构造(有参,无参),set ,get ,toSting
}
方法一直接查询映射
格式
<select id="接口名" resultMap="自定义整合后的map名称,如下">
select * from student;
</select>
<resultMap id="自定义整合后的map名称" type="A表实体类">
<association property="A表实体类需要赋值的字段属性名" column="A表内需要在B表查询的值" javaType="B表实体类" select="B表查询语句ID" />
</resultMap>
<select id="查询语句ID" resultType="B表实体类">
select * from teacher where id = #{id}
</select>
###示例
<select id="getStudents" resultMap="StudentTeacher">
select * from student;
</select>
<resultMap id="StudentTeacher" type="com.example.webdemo.entity.StudentEntity">
<association property="teacherEntity" column="tid" javaType="com.example.webdemo.entity.TeacherEntity" select="getTeacher" />
</resultMap>
<select id="getTeacher" resultType="com.example.webdemo.entity.TeacherEntity">
select * from teacher where id = #{id}
</select>
方法二 通过查询结果后映射关系
格式
<select id="接口名" resultMap="自定义映射map如下">
select a.id as aid,b.id as bid,a.name as studentname,b.name as teachename from student a left join teacher b on a.tid = b.id;
</select>
<resultMap id="自定义映射map" type="需要返回的主表实体类">
<id property="实体类字段id" column="如上查询结果id" />
<result property="实体类字段" column="如上查询结果中的字段" />
<association property="实体类字段" javaType="关联表的实体类">
<result property="关联表的实体类字段" column="如上查询结果中的字段"/>
</association>
</resultMap>
###示例
<select id="getStudents2" resultMap="studentTeache2">
select a.id as aid,b.id as bid,a.name as studentname,b.name as teachename from student a left join teacher b on a.tid = b.id;
</select>
<resultMap id="studentTeache2" type="com.example.webdemo.entity.StudentEntity">
<id property="id" column="aid" />
<result property="name" column="studentname" />
<association property="teacherEntity" javaType="com.example.webdemo.entity.TeacherEntity">
<result property="name" column="teachename"/>
</association>
</resultMap>
所有的实体类引用最好使用全路径如:com.example.webdemo.entity.TeacherEntity