欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

关于MyBatis 查询数据时属性中多对一的问题(多条数据对应一条数据)

程序员文章站 2023-03-07 13:38:33
数据准备数据表create table `teacher`( id int(10) not null, `name` varchar(30) default null, primary key (id...

数据准备

数据表

create table `teacher`(
 id int(10) not null,
 `name` varchar(30) default null,
 primary key (id)
) engine=innodb default charset=utf8;


insert into `teacher`(id,`name`) values(1,'大师');

create table `student`(
 id int(10) not null,
 `name` varchar(30) default null,
 `tid` int(10) default null,
 primary key(id),
 key `fktid` (`tid`),
 constraint `fktid` foreign key (`tid`) references `teacher` (`id`)
) engine=innodb default charset=utf8;

insert into student(`id`,`name`,`tid`) values(1,'小明',1);
insert into student(`id`,`name`,`tid`) values(2,'小红',1);
insert into student(`id`,`name`,`tid`) values(3,'小张',1);
insert into student(`id`,`name`,`tid`) values(4,'小李',1);
insert into student(`id`,`name`,`tid`) values(5,'小王',1);

teacher 类

public class teacher {
  private int id;
  private string name;
}

student 类

public class student {
  private int id;
  private string name;

  private teacher teacher;
}

查询接口

public interface studentmapper {
  // 查询嵌套处理 - 子查询
  list<student> getstudentlist();

  // 结果嵌套处理
  list<student> getstudentresult();
}

查询嵌套处理(子查询)

思路:先查询出所有学生的数据,再根据学生中关联老师的字段 tid 用一个子查询去查询老师的数据

association:处理对象

property:实体类中属性字段

column:查询结果中需要传递给子查询的字段

javatype:指定实体类

select:子查询sql

<mapper namespace="com.pro.dao.studentmapper">
  <!--
  按照查询嵌套处理
    1. 先查询所有学生信息
    2. 根据查询出来学生的tid, 接一个子查询去查老师
  -->
  <resultmap id="studentteacher" type="com.pro.pojo.student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <!--复杂属性需要单独处理, 对象: association, 集合: collection -->
    <association property="teacher" column="tid" javatype="com.pro.pojo.teacher" select="getteacher"/>
  </resultmap>

  <select id="getstudentlist" resultmap="studentteacher">
    select * from student
  </select>

  <select id="getteacher" resulttype="com.pro.pojo.teacher">
    select * from teacher where id = #{id}
  </select>
</mapper>

结果嵌套处理

思路:先把所有的信息一次性查询处理, 然后配置字段对应的实体类, 使用 association 配置

association:处理对象

property:实体类中属性字段

javatype:指定实体类

<mapper namespace="com.pro.dao.studentmapper">
  <!--
  按照结果嵌套处理
    1. 一次查询出所有学生和老师的数据
    2. 根据查询的结果配置 association 对应的属性和字段
  -->
  <resultmap id="studentresult" type="com.pro.pojo.student">
    <result column="sid" property="id"/>
    <result column="sname" property="name"/>
    <!-- 根据查询出来的结果, 去配置字段对应的实体类 -->
    <association property="teacher" javatype="com.pro.pojo.teacher">
      <result column="tname" property="name"/>
    </association>
  </resultmap>

  <select id="getstudentresult" resultmap="studentresult">
    select s.id sid, s.name sname, t.name tname from student s, teacher t where s.tid = t.id
  </select>
</mapper>

到此这篇关于mybatis 查询数据时属性中多对一的问题(多条数据对应一条数据)的文章就介绍到这了,更多相关mybatis 查询数据内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!