mybatis:一对多
Posted 小布丁value
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis:一对多相关的知识,希望对你有一定的参考价值。
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');
可以改动一下mybatis.config.xml
配置Teacher.xml
测试成功
2.查询一对多信息
问题:查找所有学生的信息以及学生对应的老师信息
按照嵌套查询处理
用resultType查不出来Teacher,怎么办呢?用resultMap
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<result property="name" column="name"/>
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getStudent" resultMap="StudentTeacher">
select * from student
</select>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id=#id
</select>
按照结果嵌套处理
<!--按照结果嵌套处理-->
<select id="getStudent" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.name tname, t.id tid from student s,teacher t where s.tid = t.id;
</select>
<resultMap id="StudentTeacher2" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
<result property="id" column="tid"/>
</association>
</resultMap>
以上是关于mybatis:一对多的主要内容,如果未能解决你的问题,请参考以下文章