解决mybatis实体类中的属性名和SQL中的字段名不一致问题

这个问题在使用mybatis的过程中会经常遇到。

一、连表查询

    <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>

各个属性介绍:

  1. id要保持一致,就是结果集的id和select的resultMap的值保持一致(使用结果集映射的只有select)
  2. result标签中的 property就是实体类的属性名,column就是SQL字段名
  3. association标签映射的是类变量,result标签映射的普通变量
  4. type 和 javatype都是实体类的名字

其实结果集映射学这些基本够了

二:嵌套查询

在SQL中设计多表查询的问题的时,有两种方式,一是多表连接,而是嵌套查询。其中多表连接常用,但是嵌套查询也应该了解

嵌套查询的结果集映射和上面有所不同

一个参数:


    <select id="getStudent" resultMap="StudentTeacher">
        select * from student
    </select>
    <select id="getTeacher" resultType="Teacher">
        select * from teacher where id=#{id}
    </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>
  1. association标签中的column为Student表的字段名,该字段将为select后面查询的参数。
  2. association标签中select属性中的查询的结果就是javatype的类型

注意:一个参数的时候,id=#{id}参数可以随意取值,多参数的时候,必须严格一致

多个参数:

    <select id="getStudent" resultMap="StudentTeacher">
        select * from student
    </select>
    <select id="getTeacher" resultType="Teacher">
        select * from teacher where id=#{id}
    </select>
    <resultMap id="StudentTeacher" type="Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <association property="teacher" column="{id=tid}" javaType="Teacher" select="getTeacher"/>
    </resultMap>
   association中column多参数配置:
   column="{key=value,key=value}"
   其实就是键值对的形式,key是传给下个sql的取值名称,value是片段一中sql查询的字段名。加上{}即是多参数,须一致。

三、collection

collection标签和association标签使用方法差不多,不过对应的多对多确实需要花时间去理解

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值