亲宝软件园·资讯

展开

Mybatis一对多与多对一查询 Mybatis一对多与多对一查询处理详解

KittyGuy 人气:1
想了解Mybatis一对多与多对一查询处理详解的相关内容吗,KittyGuy在本文为您仔细讲解Mybatis一对多与多对一查询的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:mybatis多对一查询,mybatis一对多数据查询封装,mybatis一对多查询配置详解,下面大家一起来学习吧。

要点

一对多(association)

数据库结构

tid是student的外键,是teacher表的id

JavaBean

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

mapper.java

public interface StudentMapper {
 List<Student> getStudent();
 List<Student> getStudent2();
}

Student类里面有teacher,要想查出Student中的Teacher就需要映射。

方法有二

(1)

<select id="getStudent" resultMap="StudentTeacher">
    select * from mybatis.student
  </select>
  <resultMap id="StudentTeacher" type="Student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
  </resultMap>
        <!--子查询-->
  <select id="getTeacher" resultType="Teacher">
     select * from mybatis.teacher where id=#{Anything}
  </select>

(2)

<select id="getStudent2" resultMap="StudentTeacher2">
    select * from mybatis.student as s ,mybatis.teacher as t where s.tid=t.id
  </select>
  <resultMap id="StudentTeacher2" type="Student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <association property="teacher" javaType="Teacher">
      <result property="id" column="tid"/>
      <result property="name" column="name"/>
    </association>
  </resultMap>

多对一

JavaBean

public class Teacher2 {
  private int id;
  private String name;
  //一个老师对应多个学生
  private List<Student2> students;
}
public class Student2 {
  private int id;
  private String name;
  private int tid;
}

mapper.java

public interface TeacherMapper2 {
  List<Teacher2> getTeacher(@Param("id") int id);
}

mapper.xml

<?xml version="1.0" encoding="GBK" ?>
<!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.mybatis.DAO.TeacherMapper2">
  <select id="getTeacher" parameterType="int" resultMap="teacherS">
    select s.id, s.name, s.tid,t.id as tid, t.name as tname from mybatis.student as s ,mybatis.teacher as t where s.tid=t.id and t.id=#{id}
  </select>
  <resultMap id="teacherS" type="teacher2">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
    <collection property="students" ofType="student2">
      <result property="id" column="id"/>
      <result property="name" column="name"/>
      <result property="tid" column="tid"/>
    </collection>
  </resultMap>
</mapper>

小结

加载全部内容

相关教程
猜你喜欢
用户评论