zoukankan      html  css  js  c++  java
  • 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;
    
  • 相关阅读:
    使用Docker在本地搭建Hadoop分布式集群
    微博推荐 第三个map 源码
    对象
    http无状态(stateless)
    理解http的无连接
    http响应报文之首部行
    http响应报文之状态行
    http响应报文
    http请求报文之首部行
    http请求之请求数据
  • 原文地址:https://www.cnblogs.com/ihaokun/p/10040768.html
Copyright © 2011-2022 走看看