Mybatis中字段返回值映射问题
需求说明:
返回值列表扩展字段值,不改变原有代码的基础上,增加返回值
编写类VO:
public class RegionVO extends Region {
//点位数量
private Integer nodeCount;
public Integer getNodeCount() {
return nodeCount;
}
public void setNodeCount(Integer nodeCount) {
this.nodeCount = nodeCount;
}
}
mapper.xml
<select id="selectRegionVOList" resultType="com.dkd.manage.vo.RegionVO">
SELECT
r.*,
count( n.id ) AS node_count
FROM
tb_region r
LEFT JOIN tb_node n ON r.id = n.region_id
GROUP BY
r.id
<where>
<if test="regionName != null and regionName != ''"> and region_name like concat('%', #{regionName}, '%')</if>
</where>
</select>
controller类:
@RestController
@RequestMapping("/manage/region")
public class RegionController extends BaseController
{
@Autowired
private IRegionService regionService;
/**
* 查询区域管理列表
*/
@PreAuthorize("@ss.hasPermi('manage:region:list')")
@GetMapping("/list")
public TableDataInfo list(Region region)
{
startPage();
List<RegionVO> voList = regionService.selectRegionVOList(region);
return getDataTable(voList);
}
}
浏览器测试结果:
正常情况下也是可以的,但是当时测试的时候,始终缺少字段nodeCount ;
在这里我们可以换种方案:
修改mapper.xml文件
<resultMap id="RegionVOResult" type="com.dkd.manage.vo.RegionVO">
<result property="id" column="id" />
<result property="regionName" column="region_name" />
<result property="remark" column="remark" />
<result property="createBy" column="create_by" />
<result property="updateBy" column="update_by" />
<result property="createTime" column="create_time" />
<result property="updateTime" column="update_time" />
<result property="nodeCount" column="node_count" />
</resultMap>
<select id="selectRegionVOList" resultMap="RegionVOResult">
SELECT
r.*,
count( n.id ) AS node_count
FROM
tb_region r
LEFT JOIN tb_node n ON r.id = n.region_id
GROUP BY
r.id
<where>
<if test="regionName != null and regionName != ''"> and region_name like concat('%', #{regionName}, '%')</if>
</where>
</select>
再次运行,效果也是可以的!
扩展SQL:
SELECT
re.id,
re.region_name,
re.remark,
IFNULL( tbc.node_count, 0 ) AS nodeCount,
re.create_time
FROM
tb_region re
LEFT JOIN ( SELECT region_id, count( 0 ) node_count FROM tb_node GROUP BY region_id ) tbc ON tbc.region_id = re.id
SELECT
r.*,
count( n.id ) AS node_count
FROM
tb_region r
LEFT JOIN tb_node n ON r.id = n.region_id
GROUP BY
r.id