标签:mybatis map 实体类 log4 ons each 指定 底层原理 varchar
如,
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);
<!--思路:
1.查询所有的学生信息
2.根据tid,寻找对应的老师
-->
<select id="getStudent" resultMap="StudentTeacher">
select * from student
</select>
<resultMap id="StudentTeacher" type="Student">
<result property="id" column="id"/>
<association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="Teacher">
select * from teacher where id=#{id};
</select>
<!--按照结果嵌套处理-->
<select id="getStudent2" resultMap="StudentTeacher2">
select s.id sid,s.name sname,t.name tname
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"/>
</association>
</resultMap>
回顾对比Mysql多对一查询方式:
步骤:
环境搭建
实体类
@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;
}
<select id="getTeacher" resultMap="TeacherStudent">
select s.id sid,s.name sname,t.name tname,t.id tid
from student s,teacher t
where s.tid=t.id and t.id=#{tid};
</select>
<resultMap id="TeacherStudent" type="Teacher">
<result property="id" column="tid"/>
<result property="name" column="tname"/>
<collection property="students" ofType="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<result property="tid" column="tid"/>
</collection>
</resultMap>
<select id="getTeacher2" resultMap="TeacherStudent2">
select * from mybatis.teacher where id=#{tid}
</select>
<resultMap id="TeacherStudent2" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from mybatis.student where tid=#{tid}
</select>
注意点:
保证SQL的可读性,尽量通俗易懂
注意属性名和字段名区别
可以使用日志排除错误,推荐Log4j
标签:mybatis map 实体类 log4 ons each 指定 底层原理 varchar
原文地址:https://www.cnblogs.com/CodeHuba/p/13489695.html