Mybatis一对多处理

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

数据库准备

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

建立学生的实体类

package com.feng.pojo;

import lombok.Data;

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

}

建立老师的实体类

package com.feng.pojo;

import lombok.Data;

import java.util.List;

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

    private List<Student> student;
}

编写TeacherMapper接口

package com.feng.dao;

import com.feng.pojo.Teacher;
import org.apache.ibatis.annotations.Param;

public interface TeacherMapper {
    
    
    //一对多,根据老师获取学生信息
    public Teacher getTeacher(@Param("id") int id);
}

编写TeacherMapper.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.TeacherMapper">

    <select id="getTeacher" resultMap="TeacherStudent">
       select s.id sid,s.name sname,t.id tid,t.name tname from student s,teacher t where s.tid = t.id and t.id = #{id}
    </select>

    <resultMap id="TeacherStudent" type="teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <collection property="student" ofType="student">
            <result property="name" column="sname"/>
            <result property="id" column="sid"/>
            <result property="tid" column="tid"/>
       </collection>
   </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.TeacherMapper">

    <select id="getTeacher" resultMap="TeacherStudent">
        select * from teacher where id = #{id}
    </select>

    <resultMap id="TeacherStudent" type="teacher">
        <result property="id" column="id"/>
        <collection property="student" ofType="Student" javaType="ArrayList" select="getStudent" column="id"/>
    </resultMap>

    <select id="getStudent" resultType="student">
        select * from student where tid = #{id}
    </select>

</mapper>

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

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

测试

猜你喜欢

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