Mybatis(一对多处理)

1.搭建数据库环境

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);

2.实体类

@Data
public class Student {
    
    
    private int id;
    private String name;
    private int tid;
}
@Data
public class Teacher {
    
    
    private int id;
    private  String name;
    //一个老师拥有多个学生
    private List<Student> students;
}

按照结果嵌套处理

连表查询

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

用resultMap,不用resultType是因为查询老师操作中学生对象会为空,数据库中的值与java中的实体类没有对应上, javaType是指定属性的返回值类型,ofType是指定属性中的泛型

<select id="getTeacher" resultMap="getStudent">
     select t.name tn,s.id sid,s.name sn from mybatis.teacher t,mybatis.student s where t.id=s.tid and t.id=#{id};
</select>
    <resultMap id="getStudent" type="Teacher">
        <result property="name" column="tn"/>
        <collection property="students" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="tn"/>
        </collection>
    </resultMap>

按照查询嵌套处理

public List<Teacher> getTeacher1(@Param("id") int id);
 <select id="getTeacher1" resultMap="getStudent1">
        select t.name tn from  mybatis.teacher t where id=#{id};
    </select>
    <resultMap id="getStudent1" type="Teacher">
        <result property="name" column="tn"/>
        <collection property="students" javaType="ArrayList" ofType="Student" select="getStuByTeaId" column="id"/>
    </resultMap>
    <select id="getStuByTeaId" resultType="Student">
        select *from mybatis.student;
    </select>

猜你喜欢

转载自blog.csdn.net/fhuqw/article/details/121234705
今日推荐