这里使用student和clazz之间的关系进行说明,一个student对应一个clazz,一个clazz对应多个学生
student类如下:
public class Student {
private Integer id;
private String name;
private String sex;
private Integer age;
// 关联的Clazz对象
private Clazz clazz;
}
对应数据库字段:
id name sex age clazz_id
clazz类如下:
public class Clazz {
private Integer id;
private String code;
private List<Student> students;
}
对应数据库字段:
id code
下面的selectStudent会去resultMap中找出对应的字段,然后将column="clazz_id"当做条件传入selectClazzWithId,property属性对应的实体类当中的Clazz clazz属性,javaType表示该属性对应的类型名称
<!-- 映射学生对象的resultMap -->
<resultMap id="studentResultMap" type="org.fkit.domain.Student">
<id property="id" column="id" />
<result property="name" column="name"/>
<result property="sex" column="sex"/>
<result property="age" column="age"/>
<!-- 关联映射 -->
<association property="clazz" column="clazz_id"
javaType="org.fkit.domain.Clazz"
select="selectClazzWithId"/>
</resultMap>
<!-- 根据班级id查询班级 -->
<select id="selectClazzWithId" resultType="org.fkit.domain.Clazz">
SELECT * FROM TB_CLAZZ where id = #{id}
</select>
<!-- 查询所有学生信息 -->
<select id="selectStudent" resultMap="studentResultMap">
SELECT * FROM TB_STUDENT
</select>
下面的selectClazz会去resultMap中找出对应的字段,然后将column="id"当做条件传入selectStudentWithId,property属性对应的实体类当中的Student cstudent属性,ofType表示的是集合当中类型
<!-- 映射班级对象的resultMap -->
<resultMap id="clazzResultMap" type="org.fkit.domain.Clazz">
<id property="id" column="id" />
<result property="code" column="code"/>
<!-- 班级的学生属性,因为一个班级有多个学生,所以该属性是一个集合 -->
<collection property="students" javaType="ArrayList"
column="id" ofType="org.fkit.domain.Student"
select="selectStudentWithId"/>
</resultMap>
<!-- 根据班级id查询学生 -->
<select id="selectStudentWithId" resultType="org.fkit.domain.Student">
SELECT * FROM TB_STUDENT where clazz_id = #{id}
</select>
<!-- 查询所有班级信息 -->
<select id="selectClazz" resultMap="clazzResultMap">
SELECT * FROM TB_CLAZZ
</select>
其他:
案例: 查询所有订单信息,关联查询下单用户信息。
注意: 因为一个订单信息只会是一个人下的订单,所以从查询订单信息出发关联查询用户信息为一对一查询。如果从用户信息出发查询用户下的订单信息则为一对多查询,因为一个用户可以下多个订单。
SELECT
orders.*,
user.username,
userss.address
FROM
orders,
user
WHERE orders.user_id = user.id
Po类中应该包括上边sql查询出来的所有字段,如下:
public class OrdersCustom extends Orders {
private String username;// 用户名称
private String address;// 用户地址
get/set。。。。
OrdersCustom类继承Orders类后OrdersCustom类包括了Orders类的所有字段,只需要定义用户的信息字段即可。
总结:
- 对单个对象的映射关系:
1)自动关联(偷懒的办法):可以自定义一个大而全的pojo类,然后自动映射其实是根据数据库总的字段名称和pojo中的属性名称对应.
2)手动关联: 需要指定数据库中表的字段名称和java的pojo类中的属性名称的对应关系,
使用association标签 - 对集合对象的映射关系
只能使用手动映射:指定表中字段名称和pojo中属性名称的对应关系
使用collection标签 - mybatis关联查询 --;两种方式!
一个xml里面可以写多个resultmap