mybatis查询一对多返回List<String>集合

2023年7月30日11:06:16

先看两张表

channel_auth 授权信息主表 —— channel_auth_method 授权方法表

channel_auth表 授权信息主表 channel_auth_method表 授权方法表
id 主表id auth_id 主表id
app_key 授权公钥 method 方法
app_user 授权账号

entity:

@Data
@TableName("channel_auth")
public class ChannelAuthDO {
    @TableId
    private Long id;
    private String appKey;//授权公钥
    private String appUser; //授权账号
    
    @TableField(exist = false)
    private List<String> method; //方法集合
}

查询ChannelAuthDO时,要关联channel_auth_method表,查询method,把实体中的List<String> method填充,进去

方式一:使用collection标签 中的 select

<resultMap type="ChannelAuthDO" id="BaseMap">
     <id property="id" column="id"/>
     <result property="appKey" column="app_key"/>
     <result property="appUser" column="app_user"/>

     <!-- 关联属性对应的表:ChannelAuthMethodDO的method字段 -->
     <collection property="method" ofType="String" select="select_method" column="id"/>
</resultMap>

<select id="list" resultType="ChannelAuthDO" resultMap="BaseMap">
	select id, app_key, app_user
    from channel_auth
</select>

<!--查询方法表 
		这个是映射collection 中select_method的方法  
		这里的authId对应collection 中的column="id"
-->
 <select id="select_method" resultType="string" parameterType="long">
      select method
      from channel_auth_method
      where auth_id = #{authId}
  </select>

弊端:当主表信息全部查出来以后,collection 会一个一个遍历去调用select_method方法,数据多的话会影响性能。

方式二:构造函数注入

<resultMap type="ChannelAuthDO" id="BaseMap">
	   <id property="id" column="id"/>
	   <result property="appKey" column="app_key"/>
	   <result property="appUser" column="app_user"/>
	
	   <!-- 关联属性对应的表:ChannelAuthMethodDO的method字段 -->
	   <collection property="method" ofType="java.lang.String">
	       <constructor>
	           <arg column="table_method"/>  <!-- 对号入座数据库column名称即可 -->
	       </constructor>
	   </collection>
</resultMap>

<!-- 直接用id关联,查出来的method会自动映射在List<String> method 中 -->
<select id="list" resultType="ChannelAuthDO" resultMap="BaseMap">
    select 
	     main.id,
	     main.app_key,
	     main.app_user,
	     method."method" as table_method   为区分上面的映射关系,这边重新命名
    from channel_auth main, channel_auth_method method
    where main.id = method.auth_id
</select>

弊端:会影响分页

拓展:

如果list既有List<String>又有 List<Integer>,则需要写两个collection的构造函数注入

<resultMap type="ChannelAuthDO" id="BaseMap">
	   <id property="id" column="id"/>
	   <result property="appKey" column="app_key"/>
	   <result property="appUser" column="app_user"/>
	   
	   <!-- 映射字符串集合 -->
	   <collection property="method" ofType="java.lang.String">
	       <constructor>
	           <arg column="table_method"/>  <!-- 数据库映射的column名称 -->
	       </constructor>
	   </collection>
	   
	   <!-- 映射int类型集合 -->
	   <collection property="age" ofType="java.lang.Integer">
	       <constructor>
	           <arg column="age"/>  <!-- 数据库映射的column名称 -->
	       </constructor>
	   </collection>
</resultMap>

  • 作者:Mr_ZhouR
  • 原文链接:https://blog.csdn.net/Mr_ZhouR/article/details/125633895
    更新时间:2023年7月30日11:06:16 ,共 2309 字。