mybatis一对一

前言

如果在一个实体bean里包含其它实体bean,如一个班主任只属于一个班级,一个班级也只能有一个班主任,那么在Teacher实体bean中包含Class实体bean,这时mybatis在查询到数据后会直接映射到Teacher实体中并完成对Class的映射。下面具体讲一下映射文件怎么写。

具体一对一

1.创建班主任teacher表

CREATE TABLE `teacher` (
  `teacher_no` int(11) NOT NULL,
  `teacher_name` varchar(255) NOT NULL,
  `class_no` int(11) NOT NULL,
  PRIMARY KEY (`teacher_no`)
)

创建班级class表

CREATE TABLE `class` (
  `class_no` int(11) NOT NULL,
  `class_name` varchar(255) NOT NULL,
  PRIMARY KEY (`class_no`)
)

表中数据就自己添加吧

2.创建Classes实体类

public class Classes {

    private int classNo;//课程号

    private String className;//课程名

    public int getClassNo() {
        return classNo;
    }

    public void setClassNo(int classNo) {
        this.classNo = classNo;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

}

创建Teacher实体类

public class Teacher {

    private int teacherNo;//教师号

    private String teacherName;//教师名

    private Classes classes;

    public int getTeacherNo() {
        return teacherNo;
    }

    public void setTeacherNo(int teacherNo) {
        this.teacherNo = teacherNo;
    }

    public String getTeacherName() {
        return teacherName;
    }

    public void setTeacherName(String teacherName) {
        this.teacherName = teacherName;
    }

    public Classes getClasses() {
        return classes;
    }

    public void setClasses(Classes classes) {
        this.classes = classes;
    }

}

可以看到Teacher类中包含Classes实体类。

3.mybatis映射文件配置

<?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.mycompany.dao.HelloWorldDao">

    <!-- resultMap:映射实体类和字段之间的一一对应的关系 -->
    <resultMap type="com.mycompany.entity.Teacher" id="getClassMap">
        <id property="teacherNo" column="teacher_no"/>   
        <result property="teacherName" column="teacher_name"/>
        <association property="classes" javaType="com.mycompany.entity.Classes">   
            <id property="classNo" column="class_no"/>  
            <result property="className" column="class_name"/>
        </association>
    </resultMap>

    <select id="getTeacherDetail" parameterType="int" resultMap="getClassMap">
        select * from class c, teacher t  where c.teacher_no = t.teacher_no and c.teacher_no=#{id}
    </select>

</mapper>

4.java代码

List<Teacher> list = helloWorldDao.getTeacherDetail(id);

所以,不论where条件是什么,查询出多少条Teacher,每条Teacher都对应一条Classes。

后记

一对一的关键就在于实体类中要包含另一个实体类,而且mapper映射文件中要用到association子标签,该标签用于一对一的关联查询

  • property 对象属性的名称
  • javaType 对象属性的类型
  • column 所对应的外键字段名称
  • select 使用另一个查询封装的结果
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页