Mybatis基础(六)
mybatis框架只有两种关系:一对一关系,一对多关联查询。(对用关系指的是:表的外键与被关联表的字段的对应关系)
连表查询时,查询结果字段结构不一定是一个特定的类型,所以这时使用关联查询的实现方法
一对一关联查询
实现方法:
- 业务扩展类
- resultMap
业务扩展类
业务扩展类:专门写一个类,这个类的属性就是查询结果字段。
遇到的问题:java中只能实现单继承,所以并不能使用继承两个类达到是实现一个业务扩展类。
<select id="" parameterType="" resultType="StudentBusiness">
select s.*, c.* from student s
inner join studentCard c
on s.sid = c.cid
</select>
public class StudentBusiness extends Student{
// 这时另一个类的属性,因为连表查询得到的结果是这两个类的属性
private int cardId;
private String cardInfo;
}
制作原则:继承一个属性多的,重写一个属性少的。
resultMap
制作原则:将一个类A作为属性放入另一个类B中。这样这两个类就建立起关系了。
例如:B类为Student类,A类为StudentCard类。Studnet类中拥有stuNo、stuName、card字段,StudentCard类中拥有cardId、cardInfo字段。
实现步骤:
-
通过成员属性将两个类建立起联系
-
使用resultMap将返回结果构建成B类
<select id="" parameterType="" resultMap="student_card_map">
select s.*, c.* from student s
inner join studentCard c
on s.sid = c.cid
</select>
<resultMap type="Student" id="student_card_map">
<id property="stuNo" column="stuNo"/>
<reslut property="stuName" column="stuName"/>
<!--学生证属性,学生证类型的。javaType指定属性的类型。-->
<association proerty="card" javaType="StudentCard">
<!--StudentCard类中还有属性-->
<id property="cardId" column="cardId"/>
<id property="cardInfo" column="cardInfo"/>
</association>
</resultMap>
简单类型:主键用id、非主键用result
类类型:一对一使用association标签、一对多使用collection标签。
一对多关联查询
在mybatis中一对多查询与多对一查询是一个东西,而多对多也可以使用多个一对多实现。
按照建表建立实体类规则,一对多建实体类为:将一个类A作为多个属性放入另一个类B中。这样这两个类就建立起关系了。
例如:B类为StudentClass类,A类为Student类。StudentClass拥有属性:classId、className、(List<Student>) students。Student拥有属性:stuNo、stuName。
<select id="" resultMap="class_student_map">
select c.*, s.* from student s
inner join studentclass c
on c.classId = s.classId
</select>
<resultMap type="StudentClass" resultMap="class_student_map">
<id property="classId" column="classId"/>
<result property="className" column="className"/>
<!-- 如果是描述属性的类型使用javaType、如果是描述属性的元素的类型用ofType-->
<collection property="students" ofType="Student">
<id property="stuNo" column="stuNo"/>
<result property="stuName" column="stuName"/>
</collection>
</resultMap>