MyBatis中实现多表查询如果查询的数据量大,推荐使用N+1次查询。数据量少使用联合查询。。。
一、1、Mybatis是实现多表查询方式
1.1 业务装配:对两个表编写单表查询语句,在业务(Service)把查询的两表结果合并 1.2 使用Auto Mapping 特性,在实现两表联合查询时通过别名完成映射
1.3 使用MyBatis resultMap属性进行实现
2、多表查询时,类中包含另一个类的对象的分类
2.1 单个对象
2.2 集合对象二、resultMap属性
1、resultMap标签写在mapper.xml中,由程序员控制SQL查询结果与实体类的映射关系。
1.2 默认MyBatis使用Auto Mapping特性
2、使用resultMap 标签时,select标签不写resultType属性,而是使用resultMap属性 引用resultMap标签
3、使用resultMap实现单表映射关系
3.1 数据库设计
3.2 实体类设计
3.3 xxxmapper.xml代码
1 <mapper namespace="com.bjsxt.mapper.TeacherMapper">
2 <resultMap type="Teacher" id="mymap">
3 <!-- 主键使用id标签配置映射关系-->
4 <id column="id" property="id1"/>
5 <!-- 其他列使用result标签配置映射关系 -->
6 <result column="name" property="name1"/>
7 </resultMap>
8 <select id="selall" resultMap="mymap">
9 select * from teacher
10 </select>
11 </mapper>
三、使用resultMap 实现关联单个对象(N+1方式)
4.1 N+1 查询方式,先查询出某个表的全部信息,根据这个表的信息查询另一个表的信息
4.2 与业务装配的区别:
4.2.1 之前在service里面写代码,现在由mybatis完成装配
4.3 实现步骤:
4.3.1 在Student 实现类中包含了一个Teacher 对象
4.3.2 在TeacherMapper 中提供一个查询
1 <mapper namespace="com.bjsxt.mapper.TeacherMapper">
2 <select id="selById" resultType="teacher" parameterType="int" >
3 select * from teacher where id=#{0}
4 </select>
5 </mapper>
4.3.3 在StudentMapper中
4.3.3.1 association 装配一个对象时使用(包含在student中的对象) 4.3.3.2 property 关联对象
4.3.3.3 select 通过哪个查询查询出这个对象的信息
4.3.3.4 column 把当前表的哪个列的值作为参数传递给另一个查询 4.3.3.5 大前提使用N+1方式时,如果列名和属性名相同可以不配置,使用Auto mapping特性,但是mybatis默认只会给列专配一次。。
<mapper namespace="com.bjsxt.mapper.StudentMapper">
<resultMap type="student" id="stumap