mybatis聯合查詢遇到相同欄位解決辦法
阿新 • • 發佈:2019-02-20
問題
mybatis在聯合查詢的時候,有時候會遇到相同的欄位,前面的欄位值會覆蓋後面欄位的值。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.hand.core.demos.mapper.DemokeyMapper">
<resultMap id="BaseResultMap" type="com.hand.core.demos.dto.Demokey">
<result column="id" property="id" jdbcType="DECIMAL" />
<result column="demo_id" property="demoId" jdbcType="DECIMAL" />
<result column="name" property="name" jdbcType="VARCHAR" />
</resultMap>
<!--聯合查詢 star-->
<resultMap id="WithDemoResultMap" type="com.hand.core.demos.dto.Demokey">
<result column="id" property="id" jdbcType="DECIMAL" />
<result column="demo_id" property="demoId" jdbcType="DECIMAL" />
<result column="name" property="name" jdbcType="VARCHAR" />
<association property="demos" javaType="com.hand.core.demos.dto.Demos">
<result column="id" property="id" jdbcType="DECIMAL" />
<result column="name" property="name" jdbcType="VARCHAR" />
</association>
</resultMap>
<sql id="WithDemos_Column_List">
k.id,k.demo_id,k.name,d.id,d.name
</sql>
<select id="selectWithDemos" parameterType="com.hand.core.demos.dto.Demokey" resultMap="WithDemoResultMap">
SELECT <include refid="WithDemos_Column_List"/>
from hap_demokey k LEFT JOIN hap_demos d on k.demo_id = d.id
</select>
<!--聯合查詢 end-->
</mapper>
之前想的是會一一的對映
k.id,k.demo_id,k.name,d.id,d.name 會對映 Demokey.id,Demokey.demo_id,Demokey.name,Demos.id,Demos.name
但是實際卻是這樣的:
Demokey.id,Demokey.demo_id,Demokey.name,Demokey.id,Demokey.name
解決辦法
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.hand.core.demos.mapper.DemokeyMapper">
<resultMap id="BaseResultMap" type="com.hand.core.demos.dto.Demokey">
<result column="id" property="id" jdbcType="DECIMAL" />
<result column="demo_id" property="demoId" jdbcType="DECIMAL" />
<result column="name" property="name" jdbcType="VARCHAR" />
</resultMap>
<!--聯合查詢 star-->
<resultMap id="WithDemoResultMap" type="com.hand.core.demos.dto.Demokey">
<result column="id" property="id" jdbcType="DECIMAL" />
<result column="demo_id" property="demoId" jdbcType="DECIMAL" />
<result column="name" property="name" jdbcType="VARCHAR" />
<association property="demos" javaType="com.hand.core.demos.dto.Demos">
<result column="did" property="id" jdbcType="DECIMAL" />
<result column="dname" property="name" jdbcType="VARCHAR" />
</association>
</resultMap>
<sql id="WithDemos_Column_List">
k.id,k.demo_id,k.name,d.id did,d.name dname
</sql>
<select id="selectWithDemos" parameterType="com.hand.core.demos.dto.Demokey" resultMap="WithDemoResultMap">
SELECT <include refid="WithDemos_Column_List"/>
from hap_demokey k LEFT JOIN hap_demos d on k.demo_id = d.id
</select>
<!--聯合查詢 end-->
</mapper>