1.sql语句,创建数据库
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,建立实体类
3,在dao层建立接口以及mapper.xml
4,在mybatis核心配置文件中配置mapper.xml
5,测试
查询所有学生的信息
可以看到teacher为null
多对一:
将getStudent方法的返回类型改为ResultMap
方法二:
以上就是多对一的查询
一对多
一个老师对应多个学生
<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= #{tid}
</select>
<resultMap id="TeacherStudent" type="com.briup.pojo.Teacher">
<result column="tname" property="name"></result>
<result column="tid" property="id"></result>
<collection property="students" ofType="com.briup.pojo.Student">
<result property="name" column="sname"></result>
<result property="id" column="sid"></result>
<result property="tid" column="tid"></result>
</collection>
</resultMap>
查询成功!