前言:使用 mybatis generator 生成表格對應的pojo、dao、mapper,以及對應的example的pojo、dao、mapper,自帶對單表的增刪改查方法,這裏實現一下對多表的join查詢。java
網上join多表查詢的博客很多,但避免多表相同字段名的方法沒看到比較簡單好用的sql
最後在https://blog.csdn.net/xzm_rainbow/article/details/15336933這篇13年的博客獲得了啓發。mybatis
在這裏整理一下:app
下面代碼示例:ide
在 mapper 的 xml 文件中自定義多表查詢方法以及對應的結果集.net
<!-- 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語句中起的別名code
<!-- 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中加入上述對應的associationxml
<!-- add --> <association property="residentTag" resultMap="TagResultMap" /> </resultMap>
最後,在對應實體類中要加上blog
// 加的關聯表 private ResidentTag residentTag;