MyBatis 一对多操作

表结构:

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

    // 一个老师多个学生
    private List<Student> student;
}
public class Student {
    private int id;
    private String name;
    private int tid;
}

XML文件:

方式一:连表查询

<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="Teacher">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
    <collection property="student" ofType="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
    </collection>
</resultMap>

方式二:子查询

<select id="getTeacher2" resultMap="TeacherStudent2">
    select * from teacher where id = #{tid};
</select>

<resultMap id="TeacherStudent2" type="Teacher">
    <collection property="student" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>

<select id="getStudentByTeacherId" resultType="Student">
    select * from student where tid = #{tid}
</select>

测试文件:

public class MyTest {

    @Test
    public void getTeacherTest() {

        SqlSession sqlSession = MybatisUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacher2(1);


        System.out.println(teacher);


        sqlSession.close();
    }
}

小结:

  1. 关联查询 -association  【多对一】
  2. 集合  -collection  【一对多】
  3. javaType & ofType
    1. javaType 用来指定实体类中属性的类型
    2. ofType 用来指定映射到List或者集合中的pojo类型,泛指中的约束类型! 

注意点:

  • 保证SQL的可读性,尽量保证通俗易懂
  • 注意一对多和多对一中,属性名和字段名的问题!
  • 如果问题不好排错,可以使用日志,推荐使用Log4j!
原文地址:https://www.cnblogs.com/shangwei/p/15267342.html