当多表联查时,分析清除每个表之间的关系,通过java代码建立实体类之间的关系
一对一,一对多,多对一,多对多
通常将多对多的关系,进行拆分,通过建立第三张表去转化为一对一的关系
多表联查时,需要将每个映射关系都写出来
不管一对一,一对多,都要分析清除两个表,哪张表作为主表,哪张表作为次表
在java中的关系为一个类的对象(次表)作为另一个类(主表)的属性存在
一、通过写mapper文件实现
一对一关系--->association
resultMap属性 是返回结果的类型
result 写数据库表的字段名和java中实体类的属性,两个一一对应
association 的 property值为 A类作为B类的属性存在,那么值为 A类 类型的对象
<resultMap type="Student" id="stu_class_Map">
<result column="sid" property="sid"/>
<result column="sname" property="sname"/>
<result column="birthday" property="birthday"/>
<result column="ssex" property="ssex"/>
<result column="classid" property="classid"/>
<!-- 一对一 -->
<association property="bj">
<result column="classid" property="classid"/>
<result column="classname" property="classname"/>
</association>
</resultMap>
<select id="findStudentAndClass" resultMap="stu_class_Map">
select * from student left join class on student.classid = class.classid
</select>
一对多关系--->collection
因为为一对多关系,所以是个集合来存储这个类型的对象
collection标签里的 ofType属性就很重要,他的值为 集合当中要保存 的对象 的类型
<resultMap type="BanJi" id="class_stu_Map">
<result column="classid" property="classid"/>
<result column="classname" property="classname"/>
<!-- 一对多 -->
<collection property="stulist" ofType="Student">
<result column="sid" property="sid"/>
<result column="sname" property="sname"/>
<result column="birthday" property="birthday"/>
<result column="ssex" property="ssex"/>
<result column="classid" property="classid"/>
</collection>
</resultMap>
<select id="findBanJiAndStudent" resultMap="class_stu_Map">
select * from class left join student on student.classid = class.classid
</select>
二、通过注解实现
@Results 结果映射
每个 @Results 可以包含多个 @Result,其中可以通过 id 属性来判断是否为主键。
一对一
@One( Select = 一对一查询方法, fetchType = FetchType.EAGER )
FetchType.lazy 是延时加载,FetchType.EAGER 是即时加载。
通过 classid 查询班级信息的语句
@Select("select * from class where classid = #{value}")
public BanJi findBanJiByClassid(int classid);
一个学生对应一个班级
//一对一映射 one @One注解
@Results({
//column 为数据库里的字段名 property 为实体类中的属性 两个一一对应
@Result(column = "classid",property = "classid"),
@Result(column = "classid",property = "bj",
one = @One(
// 整个班级的信息,通过查询班级的方法获得
//方法所在位置
select = "com.apesource.mapper.BanJiMapper.findBanJiByClassid"
)
)
})
//不能写多表联查语句
@Select("select * from student")
public List<Student> findStudentAndClass();
一对多
@Many( Select = 一对多查询方法, fetchType = FetchType.EAGER )
FetchType.lazy 是延时加载,FetchType.EAGER 是即时加载。
通过sid查询学生信息的语句
@Select("select * from student where sid = #{value}")
public Student findStudentBySid(int sid);
一个班级对应多个学生
//一对多映射 many @Many注解
@Results({
//column 为数据库里的字段名 property 为实体类中的属性 两个一一对应
@Result(column = "classid",property = "classid"),
@Result(column = "classid",property = "stulist",
many = @Many(
// 每个班级的学生信息,通过查询学生的方法获得
//方法所在位置
select = "com.apesource.mapper.StudentMapper.findStudentBySid"
)
)
})
//不能写多表联查语句
@Select("select * from class")
public List<BanJi> findBanJiAndStudent();