【Mybatis】ResultMap标签

1. <resultMap>标签写在mapper.xml中,是程序员控制SQL查询结果和实体类的映射关系

1.1 Mybatis默认使用AutoMapping属性

2. 使用<resultMap>标签时,<select>标签中不写<resultType>属性,而使用 resultMap 属性引用<resultMap>标签

 

3. 使用resultMap实现单表映射关系

3.1 数据库设计

3.2 实体类设计

public class Teacher{
    private int id1;
    private int name1;
}

3.3 mapper.xml代码

主键使用id标签,其他列使用result标签

<resultMap type="teacher" id="mymap">
<!-- 主键使用 id 标签配置映射关系 -->
<id column="id" property="id1" />
<!-- 其他列使用 result 标签配置映射关系 -->
<result column="name" property="name1"/>
</resultMap>
<select id="selAll" resultMap="mymap">
select * from teacher
</select>

4. 使用resultMap实现关联对象(N+1)方式

4.1 N+1查询方式,先查出某个表的信息,再根据查出的这个表的信息查询其他表的信息!

4.2 与业务装配的区别:

           在service里面的代码,由mybatis完成装配!

4.3 实现步骤:

           4.3.1 在Student实现类中包含了一个Teacher对象

                    

public class Student {
private int id;
private String name;
private int age;
private int tid;
private Teacher teacher;

                     4.3.2  在TeacherMapper中提供一个查询

                               

<select id="selById" resultType="teacher"
parameterType="int">
select * from teacher where id=#{0}
</select>

                       4.3.3 在StudentMapper中

                     1.<association>装配一个对象时使用

                     2. property : 在对象类中的属性名

                     3. select :通过哪个查询查询出这个对象的信息

                     4. 把当前表的哪个列的值做为参数传递给另 一个查询

                    5. 大前提使用 N+1 方式.时如果列名和属性名相同可 以不配置,使用 Auto mapping 特性.但是 mybatis 默认只会给列 专                                     配一次。

<resultMap type="student" id="stuMap">
<result column="tid" property="tid"/>
<!-- 如果关联一个对象 -->
<association property="teacher"
select="com.bjsxt.mapper.TeacherMapper.selById"
column="tid"></association>
</resultMap>
<select id="selAll" resultMap="stuMap">
select * from student
</select>

5. 使用 resultMap 实现关联单个对象(联合查询方式)

5.1 只需要编写一个SQL,在StudentMapper中添加下面效果

      5.1.1 <associotion />只要专配一个对象就用这个标签

      5.1.2 此时把<association/>当成小的<resultMap>看待

      5.1.3 javaType 属性: <association/>专配完以后什么类型的对象,取值是一个实体类(或者是类的别名)

      5.1.4 property属性: 是关联对象类中的 新建的对象名;

<resultMap type="Student" id="stuMap1">
    <id column="sid" property="id"/>
    <result column="sname" property="name"/>
    <result column="age" property="age"/>
    <result column="tid" property="tid"/>
    <association property="teacher"javaType="Teacher" >
        <id column="tid" property="id"/>
        <result column="tname" property="name"/>
    </association>
</resultMap>
<select id="selAll1" resultMap="stuMap1">
select s.id sid,s.name sname,age age,t.id
tid,t.name tname FROM student s left outer join teacher
t on s.tid=t.id
</select>

 

6. N+1 方式和联合查询方式对比

6.1 N+1:需求不确定时.

6.2 联合查询:需求中确定查询时两个表一定都查询.

缺点:效率低

适用场景: 有的时候需要查询学生同时查询老师,有的时候只 需要查询学生

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值