mybatis中查询用户列表信息List<UserInfo>,UserInfo带有区域id信息areaId,需要根据areaId查询多级父级区域名称并拼接命名为areaName,areaName赋值给UserInfo
时间: 2024-03-02 17:50:17 浏览: 58
可以使用MyBatis的递归查询和resultMap来实现。具体步骤如下:
1. 在UserInfo实体类中添加一个String类型的属性areaName,用来存放查询出来的父级区域名称。
2. 编写SQL查询语句,使用递归查询和CONCAT函数拼接父级区域名称和子级区域名称,最后使用AS关键字将拼接后的字段命名为areaName,示例代码如下:
```
WITH RECURSIVE cte AS (
SELECT
a.area_id,
a.area_name,
a.parent_id,
CAST(a.area_name AS CHAR(200)) AS area_name_chain
FROM area_info a
WHERE a.area_id = #{areaId}
UNION ALL
SELECT
a2.area_id,
a2.area_name,
a2.parent_id,
CONCAT(cte.area_name_chain, '-', a2.area_name) AS area_name_chain
FROM area_info a2
INNER JOIN cte ON a2.area_id = cte.parent_id
)
SELECT u.*, cte.area_name_chain AS areaName
FROM user_info u
LEFT JOIN cte ON u.area_id = cte.area_id
```
3. 在Mapper.xml文件中添加resultMap,用来映射查询结果到UserInfo实体类中。resultMap中使用association标签来配置一对一映射关系,示例代码如下:
```
<resultMap id="userInfoMap" type="UserInfo">
<id property="userId" column="user_id"/>
<result property="userName" column="user_name"/>
<result property="areaId" column="area_id"/>
<result property="areaName" column="areaName"/>
<association property="area" javaType="AreaInfo">
<id property="areaId" column="area_id"/>
<result property="areaName" column="area_name"/>
<result property="parentId" column="parent_id"/>
</association>
</resultMap>
```
4. 在Mapper.xml文件中使用resultMap来查询用户列表信息,示例代码如下:
```
<select id="getUserInfoList" resultMap="userInfoMap">
WITH RECURSIVE cte AS (
SELECT
a.area_id,
a.area_name,
a.parent_id,
CAST(a.area_name AS CHAR(200)) AS area_name_chain
FROM area_info a
WHERE a.area_id = #{areaId}
UNION ALL
SELECT
a2.area_id,
a2.area_name,
a2.parent_id,
CONCAT(cte.area_name_chain, '-', a2.area_name) AS area_name_chain
FROM area_info a2
INNER JOIN cte ON a2.area_id = cte.parent_id
)
SELECT u.*, cte.area_name_chain AS areaName
FROM user_info u
LEFT JOIN cte ON u.area_id = cte.area_id
</select>
```
5. 在Java代码中调用Mapper的getUserInfoList方法,即可获取带有多级父级区域名称的用户列表信息。
阅读全文