由于查询字段和表名都要支持动态配置,故查询返回值需要为List
查询结果列需要支持自动映射,不配置类属性和数据库字段的映射关系。
查询需要支持一对多关联查询。
Mybatis支持2种常见返回值。
1. 在resultType中配置一个Pojo类,Mybatis会自动根据命名规则将SQL语句中的字段转换成pojo类中的属性。
2. 使用resultMap,一般是需要手供配置映射关系。
要实现描述的功能,可以使用resultMap的collection元素,并且将resultMap的autoMapping="true"让resultMap支持自动映射了(默认是false)并将type="map"。然后在SQL中进行表关联。就可以将返回值映射为Map了。
resultMap和SQL配置。代码参数如下:
- <resultMap id="listDataMap" type="map" autoMapping="true" >
- <collection property="entryList" ofType="com.ruoyi.quartz.domain.SynDataEntry" autoMapping="true" javaType="list">
- collection>
- resultMap>
-
- <select id="listDataByConfig" resultMap="listDataMap">
- select
- <foreach collection="objectConfig.synFieldConfigList"
- item="item" open="" close="" separator=",">
- <if test='(item.srcField != null and item.srcField.trim() != "")
- and (item.srcType == null or (item.srcType != null and !item.srcType.trim().toUpperCase().contains("LIST")))'>
- t.${item.srcField}
- if>
- foreach>
- ,de.*
- from ${objectConfig.srcObject} t
- left join syn_data_entry de on de.object_id = ${objectConfig.id} and de.syn_data_id = t.id
- <trim prefix="WHERE" suffixOverrides="and">
- t.task_id = #{task.id} and
- <foreach collection="objectConfig.synFieldConfigList"
- item="item" open="" close="" separator=" and ">
- <if test="item.conditional == '1'.toString()
- and item.targetValue != null
- and item.targetValue != ''
- and item.delFlag == '0'.toString()
- and item.srcField != null
- and item.srcField != ''
- ">
- t.${item.srcField} ${item.targetValue}
- if>
- foreach>
- trim>
- select>
上面的SQL,select后面的字段名,表名都是根据配置对象动态生成的。
objectConfig对应的是表配置对象。
synFieldConfigList对应的是字段配置对象
动态的数据表可能还会存在子表关联数据,也就是sql中的syn_data_entry表。
Mapper代码参考:
- /**
- * 根据对象配置,动态查询数据。还会读取同步数据子表。
- * @author namelessmyth
- * @return List
- */
- public List
- @Param("task") SynTask task,
- @Param("objectConfig") SynObjectConfig objectConfig
- );