Mybatis一对多嵌套查询解决单字段多数据分割(,)问题

有时候数据库的某个字段可能是多个id或多个值,这个时候我们想拿到里面的所有值并且映射到对应实体集合里应该怎么做呢?
可以观察数据是以逗号多条隔开存放的

例子

mapper文件中

<resultMap id="MonitorModelResultMap" type="com.jeeplus.modules.system.entity.MonitorModel">//确定映射关系一对多
		<id property="id" column="id"/>
		<result property="model" column="model"/>
        <result property="param" column="param"/>
		<result property="manufacturer" column="manufacturer"/>
		<collection property="monitorFactors" select="findInFactor"  column="monitor_factor_ids" ofType="MonitorFactor">// 嵌套查询 column代表使用的参数传入到select里的Sql 结果返回到这个集合中
		</collection>
	</resultMap>

嵌套查询语句 使用find_in_set函数来查询出多个数据

<select id="findInFactor" parameterType="string"  resultType="MonitorFactor"> //参数来源自collection 标签里的column
		select f.id,f.name,f.fcode 
		from monitor_factor f
		where find_in_set(f.id,#{ids})!=0    
	</select>

最后查询整个数据

<select id="findList" resultMap="MonitorModelResultMap">
       select id,model,monitor_factor_ids,param,manufacturer from monitor_model
    </select>

**

可能会出现的问题:Json格式解析失败

解决方法

@JsonIgnoreProperties(value = { "handler" }) 
在 json 序列化时忽略 bean 中的一些不需要转化的属性  加在一对多关系的一实体类上

**

追加: 集合为 普通类型字符串分割时

<select id="QueryNetWork" parameterType="string" resultType="string">
		select
		SUBSTRING_INDEX(SUBSTRING_INDEX(#{network_levels},',',help_topic_id+1),',',-1)
		from mysql.help_topic
		where 
		help_topic_id&lt;length(#{network_levels})length(replace({network_levels},',',''))+1
	</select>

二次追加:用函数来将一列字段拼成一串字符串

有的时候会遇见SQL语句条件要IN做查询的 我们正好需要一串连续的信息
但是会碰见这种情况
在这里插入图片描述
这个时候我们使用函数来解决
将group by产生的同一个分组中的值连接起来,返回一个字符串结果

SELECT GROUP_CONCAT(查询的字段名) FROM tb_site_auth where 自定义条件'  

大功告成!
在这里插入图片描述

发布了6 篇原创文章 · 获赞 0 · 访问量 56

猜你喜欢

转载自blog.csdn.net/zangqi123/article/details/105271648