mybatis逆向工程,实现join多表查询,避免多表相同字段名的陷阱

mybatis逆向工程,实现join多表查询,避免多表相同字段名的陷阱

​ 前言:使用 mybatis generator 生成表格对应的pojo、dao、mapper,以及对应的example的pojo、dao、mapper,自带对单表的增删改查方法,这里实现一下对多表的join查询。

​ 网上join多表查询的博客不少,但避免多表相同字段名的方法没看到比较简单好用的

​ 最后在https://blog.csdn.net/xzm_rainbow/article/details/15336933这篇13年的博客得到了启发。

​ 在这里整理一下:

  1. SQL 语句给相同字段起别名
  2. 给 resultMap 加上一个 association
  3. 给 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;

转载于:https://www.cnblogs.com/ihaokun/p/10040768.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值