多对一 : 从多的一方来查询一的一方,根据学生id查询学生信息并携带班级信息。
select * from tb_stu s join tb_class c on s.class_id=c.cid where stu_id=1
实体类:
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
private int id;
private String name;
private int age;
private String sex;
private Integer classId;
//学生所属的班级
private Clazz clazz;
}
把联表查询体现到实体类上。
package com.lmy.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Clazz {
private Integer cid;
private String cname;
}
xml:
<resultMap id="baseMap" type="com.lmy.entity.Student">
<id column="stu_id" property="id"/>
<result column="stu_name" property="name"/>
<result column="stu_age" property="age"/>
<result column="sex" property="sex"/>
<result column="class_id" property="classId"/>
<!--association: 表示一的一方
property: 属性名
javaType: 该属性名对应的数据类型
-->
<association property="clazz" javaType="com.lmy.entity.Clazz">
<id column="cid" property="cid"/>
<result column="cname" property="cname"/>
</association>
</resultMap>
<select id="findStudentById" resultMap="baseMap">
select * from tb_stu s join tb_class c on s.class_id=c.cid where stu_id=#{id}
</select>
方法二 :
返回类型就用map封装(不推荐 )
根据学生编号查询学员信息以及班级信息
public Map findById(Integer id);
<!--key:value-->
<select id="findById" resultType="java.util.Map">
select <include refid="aa"/> from tb_stu s join tb_class c on s.class_id=c.id where s.id=#{id}
</select>