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

先看两张表

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 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"/>             <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>    <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"/> 	 	    	   <collection property="method" ofType="java.lang.String"> 	       <constructor> 	           <arg column="table_method"/>   	       constructor> 	   collection> resultMap>   <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又有 List,则需要写两个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"/>   	       constructor> 	   collection> 	    	    	   <collection property="age" ofType="java.lang.Integer"> 	       <constructor> 	           <arg column="age"/>   	       constructor> 	   collection> resultMap>