Mybatis多对一处理

多对一就好比多名学生对应一名老师

数据库准备

建立好一个学生表,以及老师表
并学生表中设置一个tid对应老师的id

建立学生的实体类

package com.feng.pojo;

import lombok.Data;

@Data
public class Student {
    
    
    private int id;
    private String name;
    private int tid;

    private Teacher teacher;
}

建立老师的实体类

package com.feng.pojo;

import lombok.Data;

import java.util.List;

@Data
public class Teacher {
    
    
    private int id;
    private String name;
}

编写StudentMapper接口

package com.feng.dao;

import com.feng.pojo.Student;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface StudentMapper {
    
    
    //多对一,多名同学对应一名老师
    public List<Student> getAll();
}

编写StudentMapper.xml配置文件

按结果嵌套查询

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.feng.dao.StudentMapper">

<!--    按结果嵌套查询-->
   <select id="getAll" resultMap="Student">
       select s.id sid,s.name sname,t.id tid,t.name tname from student s,teacher t where s.tid = t.id
   </select>

    <resultMap id="Student" type="Student">
        <id property="id" column="sid"/>
       <result property="name" column="sname"/>
        <result property="tid" column="tid"/>
        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname"/>
           <result property="id" column="tid"/>
       </association>
    </resultMap>

</mapper>

按查询嵌套处理

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.feng.dao.StudentMapper">

    <select id="getAll" resultMap="StudentTeacher">
        select * from student
    </select>

    <resultMap id="StudentTeacher" type="student">
        <result property="tid" column="tid"/>
        <association property="teacher" column="tid" javaType="Teacher" select="teacher"/>
    </resultMap>

    <select id="teacher" resultType="Teacher">
        select * from teacher where id = #{tid}
    </select>

</mapper>

因为学生类中对应的是老师对象,所以用:associatiom
以上两种方法任选一种都可

在核心配置文件是对其进行注册

测试

猜你喜欢

转载自blog.csdn.net/shuati2000/article/details/120947084