mybatis逆向工程,實現join多表查詢,避免多表相同字段名的陷阱
前言:使用 mybatis generator 生成表格對應的pojo、dao、mapper,以及對應的example的pojo、dao、mapper,自帶對單表的增刪改查方法,這里實現一下對多表的join查詢。
網上join多表查詢的博客不少,但避免多表相同字段名的方法沒看到比較簡單好用的
最后在https://blog.csdn.net/xzm_rainbow/article/details/15336933這篇13年的博客得到了啟發。
在這里整理一下:
- SQL 語句給相同字段起別名
- 給 resultMap 加上一個 association
- 給 association 中的 result 對應列改 column 為第一步中起的別名
下面代碼示例:
在 mapper 的 xml 文件中自定義多表查詢方法以及對應的結果集
<!-- self defined -->
<sql id="Base_Column_List_With_Tag">
resident_detail.id, address, base_case, relation, resident_detail.name, gender, birthday, identity, nation, status,
military, education, telephone, company, marriage, health, poverty, place, security_state,
property_name, property_number, area, marriage_number, marriage_date, contraception_method,
only_date, boys, girls, remark, enter_case, care_type, update_time, tag_id, resident_tag.name "tag_name"
</sql>
<!-- self defined -->
<select id="selectByExampleWithTag" parameterType="club.iashe.pojo.ResidentDetailExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List_With_Tag" />
from resident_detail
LEFT JOIN resident_tag ON resident_detail.tag_id = resident_tag.id
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
</select>
注意:原本對應的列應該是name,這里改成tag_name 這個上面SQL語句中起的別名
<!-- add -->
<resultMap id="TagResultMap" type="club.iashe.pojo.ResidentTag">
<id column="tag_id" jdbcType="INTEGER" property="id" />
<result column="tag_name" jdbcType="VARCHAR" property="name" />
<result column="pid" jdbcType="INTEGER" property="pid" />
<result column="path" jdbcType="VARCHAR" property="path" />
<result column="level" jdbcType="INTEGER" property="level" />
</resultMap>
在原本主類的resultMap中加入上述對應的association
<!-- add -->
<association property="residentTag" resultMap="TagResultMap" />
</resultMap>
最后,在對應實體類中要加上
// 加的關聯表
private ResidentTag residentTag;
