复杂查询环境搭建及一对多和多对一
一,测试环境搭建
1.导入lombok
2.在数据库中新建两个表teacher,student
3.新建实体类Teacher,Student
4.建立Mapper接口
5.在核心配置文件中绑定注册我们的Mapper或者文件
6.测试查询是否成功
二,多对一处理
学生实体类
老师实体类
1.按照查询嵌套处理
<select id="getStudent" resultMap="StudentTeacher">
select * from student
</select>
<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="getTeacher" resultType="Teacher">
select * from teacher where id=#{id}
</select>
2.按照结果嵌套处理
<select id="getStudentT" resultMap="StudentTeacherT">
select s.id sid,s.name sname,t.name tname
from student s,teacher t
where s.tid=t.id;
</select>
<resultMap id="StudentTeacherT" type="Student">
<result property="id" column="sid"/>
<result property="name" column="sname"/>
<association property="teacher" javaType="Teacher">
<result property="name" column="tname"/>
</association>
</resultMap>
三,一对多处理
学生实体类
老师实体类
1.按结果嵌套处理
<select id="getTeacherT" 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>
2.按查询嵌套处理
<select id="getTeacherTh" resultMap="TeacherStudentTh">
select * from mybatis.teacher where id=#{tid}
</select>
<resultMap id="TeacherStudentTh" type="Teacher">
<collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="Student">
select * from student where tid=#{tid}
</select>
建议用按结果嵌套处理方式!!!
小结
1.关联:association【多对一】
2.集合:collection 【一对多】
3.javaType & ofType
1.javaType用来指定实体类中的属性
2.ofType用来指定映射到List或者集合中的pojo类型,泛型中的约束类型
注意点:
保证SQL的可读性,尽量保证通俗易懂
注意一对多和多对一中,属性名和字段的问题
如果问题不好排查错误,可以使用日志,建议使用Log4j