在使用resultMap对查询进行装填时,出现字段名重复,一致的情况下查询数据重叠的情况,

问题1:在使用resultMap对查询进行装填时,出现字段名重复,一致的情况下查询数据重叠的情况,

举例:我的主表为Teacher 存在属性:name

且存在两个外键student_id, Student表中也存在属性name

school_id,School表中也存在属性name

使用result进行装填:

<resultMap id="TeacherMap" type="Teacher">
     <id property="id" column="id"></id>
     <result property="name" column="name"></result>
     <association property="Student" resultMap="Student">
     </association>
     <association property="School" resultMap="School">
     </association>
 </resultMap>
​
 <resultMap id="Student" type="com.wangqi.model.Student">
        <id property="id" column="ServiceType_id"></id>
        <result property="name" column="name"></result>
 </resultMap>
​
 <resultMap id="School" type="com.wangqi.model.School">
        <id property="id" column="ServiceWriter_id"></id>
        <result property="name" column="name"></result>
 </resultMap>
​
<select id="getAll"  resultMap="ServiceItemMap">
        SELECT SI.*,ST.`name` SW.`NAME` 
        FROM `Teacher` SI
                 LEFT JOIN Student ST ON SI.`student_id`=ST.`id`
                 LEFT JOIN School SW ON SI.`school_id`=SW.`id`
        ORDER BY SI.`id`
 </select>

使用如上装填语句查询语句,所查询结果会出现数据重叠:

    id:1,name:李老师,Student{id=2,name:李老师},School{id:698,name:李老师}

如上所示,发现所有name属性都被主表的name属性覆盖了,原因时,当column相同时,程序默认把他当成同一个属性处理,

同样明显可以发现,我的id属性是对的,因为我的两表中的id都是主表中的外键,有专门的名字:ServiceType_id ,ServiceWriter_id

在column中我就使用了这两个名字,相当于起了别名,所以三个id是不相同的,要解决这个,就需要保证三个的name属性各不相同,就需要起别名:

首先在sql语句中就行更改:  

SELECT SI.*,ST.`name` tname SW.`NAME` wname  
        FROM `Teacher` SI
                LEFT JOIN Student ST ON SI.`student_id`=ST.`id`
                 LEFT JOIN School SW ON SI.`school_id`=SW.`id`
        ORDER BY SI.`id`

如上所示,仔细观察可以发现,我在后面两表中添加了一个别名分别是tname,wname 通过别名我们就可以保证三个表的属性字段不一致,起了别名之后,我们同样需要更改填充语句:

<resultMap id="TeacherMap" type="Teacher">
     <id property="id" column="id"></id>
     <result property="name" column="name"></result>
     <association property="Student" resultMap="Student">
     </association>
     <association property="School" resultMap="School">
     </association>
 </resultMap>
​
 <resultMap id="Student" type="com.wangqi.model.Student">
        <id property="id" column="ServiceType_id"></id>
        <result property="name" column="tname"></result>
 </resultMap>
​
 <resultMap id="School" type="com.wangqi.model.School">
        <id property="id" column="ServiceWriter_id"></id>
        <result property="name" column="wname"></result>
 </resultMap>

将column属性旧值更改为我们新建立的别名,再次进行查询,结果如下

    id:1,name:李老师,Student{id=2,name:王小明},School{id:698,name:家里蹲大学}

发现所有的数据都出现了,同样在属性很多的情况下,如果有字段名相同的情况,可以用这个办法解决,如果字段名不相同,可以不起别名,但为了后续在增加方便,还是写上比较好。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值