resultMap 使用

resultmap标签是mybatis框架中常用的一个元素,也是非常重要的映射元素,用于实现mybatis的高级映射.

其应用场景:

1)表中字段与pojo类中属性名不一致时,(如stu_id/stuId).

<resultMap type="返回类型全限定名" id="命名">
    <id property="id" column="id" />
    <result property="name" column="name"/>
    <result property="note" column="note"/>    
</resultMap>

使用方法如上,type为返回类型全限定名,id为自己为resultmap定义的名字,在sql标签上resultmap出写id,resultmap中<id>必须是表中定义的主键,<result>为表中其他属性,其中的property属性为pojo定义的属性名,column为表中的字段名.

2)sql语句嵌套查询:当我们查询的是1对n关系时,可以选择collection元素,同样也是property属性为pojo定义的属性名,column为表中的字段名,select属性指向全限定名的另一个Dao层的方法.

<resultMap type="返回类型全限定名" id="命名">
    <id property="id" column="id" />
    <result property="name" column="name"/>
    <result property="note" column="note"/>    
    <!-- collection一般应用于one2many查询 -->
    <collection property="menuIds" column="id">
        <select="全限定类名"/>
    </collection>
</resultMap>

3)多表关联查询:通过左外或者右外连接,将所需的表关联在一起进行查询,将基准表的信息写在<id><result>中,关联的表一个表写在一个<collection>中,ofType属性为property数组中,单个数据的类型.

<select id="findObjectById" resultMap="sysRoleMenuVo">
    select r.id,r.name,r.note,rm.menu_id
    from sys_roles r left join sys_role_menus rm
    on r.id=rm.role_id
    where r.id=#{id}
</select>

<resultMap type="com.cy.pj.sys.pojo.SysRoleMenuVo"
    id="sysRoleMenuVo">
    <id property="id" column="id" />
    <result property="name" column="name"/>
    <result property="note" column="note"/>
    <!-- collection一般应用于one2many查询 -->
    <collection property="menuIds" ofType="integer">
        <result column="menu_id"/>
    </collection>
</resultMap>
association和collection

在数据层进行多表查询时,除了在resultmap中用上述提到的collection外还可以使用association.

我们需要区分这两个的差别:
association是在查询1->1或n->1时使用;
collection是在查询1->n时使用;

大家可能会分不清1对1/1对n/n对1是怎么来判定的?

举个例子:
例如有一个班级表/一个学生表,都知道肯定是一个班级对应多个学生;
那我们现在是需要在查询学生时将其所在的班级也查询出来,这时就是n对1的关系-->就要使用association.
那我们现在是如果是需要在查询班级时将所在这个班级的学生都查询出来,这时就是1对n的关系-->就要使用collection.

<collection property="students" ofType="com.glj.pojo.Student"
column="id" javaType="ArrayList"
select="com.glj.mapper.StudentMapper.selectStudentByClazzId"/>
    <id property="id" column="id"/>
    <result property="name" column="name"/>
    <result property="sex" column="sex"/>
    <result property="age" column="age"/>
</collection>
<association property="clazz" javaType="com.glj.pojo.Clazz"/>
    <id property="id" column="id"/>
    <result property="code" column="code"/>
    <result property="name" column="name"/>
</association>
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值