阅读 66

MyBatis 一对多操作

表结构:

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

    // 一个老师多个学生
    private List 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

文章分类
代码人生
文章标签
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐