MyBatis一对多、多对一映射

表格:

Student

字段 类型 备注
id int 主键
name varchar2 姓名
tid int 教师id

Teacher

字段 类型 备注
id int 主键
name varchar 姓名

多对一(或者一对一):association

Student类

public class Student {
    private int id;
    private String name;
    private Teacher teacher;
}

Teacher类

public class Teacher {
    private int id;
    private String name;
}

第一种,按照结果嵌套查询

这种就简单的理解为 :

我们已经把需要的表并在一起了,我们只需要选择我们需要的属性进行映射就行了。

<select id="getStudent2" resultMap="StudentTeacher2">
    select  s.id sid,s.name sname, t.name tname
    from student s, teacher t
    where s.tid = t.id
select>

<resultMap id="StudentTeacher2" type="student">
    <result property="id" column="sid"/>
    <result property="name" column="name"/>
    <association property="teacher" javaType="teacher">
        <result property="name" column="tname"/>
    association>
resultMap>
    

第二种:按查询进行嵌套处理

这中就简单的理解为子查询

我们先查学生表的所有信息,将查到的tid 给子查询,让子查询找到对应的数据,再把结果返回

<select id="getStudent" resultMap="StudentTeacher">
    select * from student
    
select>

<resultMap id="StudentTeacher" type="student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <association property="teacher" javaType="teacher" select="getTeacher"column="tid"/>
resultMap>


<select id="getTeacher" resultType="teacher">
    select * from teacher where id = #{??};
select>

一对多:collections

Student类

public class Student2 {
    private int id;
    private String name;
    private int tid;//关联老师
}

Teacher类

public class Teacher2 {
    private int id;
    private String name;
    private List<Student> students;
}

第一种,按照结果嵌套查询

<select id="getTeacher" resultMap="TeacherStudent">
    select s.id sid, s.name sname, t.name tname, t.id tid
    from student s,teacher t
    where s.tid = t.id and t.id = #{tid}
select>

<resultMap id="TeacherStudent" type="Teacher2">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>

    <collection property="students" javaType="ArrayList" ofType="Student2">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
    collection>
resultMap>
    

第二种:按照查询进行嵌套

<select id="getTeacherById" resultMap="TeacherStudent">
	select id ddd, name from teacher where id = #{tid}
select>

<resultMap id="TeacherStudent" type="Teacher2">
	<result property="id" column="ddd"/>
	<result property="name" column="name"/>
	<collection property="students" javaType="ArrayList" ofType="Student2"
            select="getStudentByTid" column="ddd"/>
resultMap>

<select id="getStudentByTid" resultType="student2">
	select * from student where tid = #{hh}
select>

有错误请指正,共同学习。

你可能感兴趣的:(mybatis,java,数据库)