Mybatis新增save结束后自动返回主键id

1.使用场景

save操作之前实体类中id为null,save之后自动返回带id的实体类

@Override
    public ChartPagePanel save(ChartPagePanel entity) {
        UserDetails user = SecurityContextHolder.getUserDetails();
        entity.setCreateUser(user.getUsername());
        entity.setLastModifyUser(user.getUsername());
        //entity中的id为null
        chartPagePanelMapper.save(entity);
        //经过save操作后自动返回带id的entity
        // savePanelManage(entity);	其中的entity带有id
        savePanelManage(entity);
        return entity;
    }

    @Transactional
    public void savePanelManage(ChartPagePanel entity){
        if(entity.getChartPageManges()!=null && entity.getChartPageManges().size()>0) {
            Map<String, Object> map = new HashMap<>();
            for (int i = 0; i < entity.getChartPageManges().size(); i++) {
                int manageId = entity.getChartPageManges().get(i).getId();
                map.put("manageId", manageId);
                map.put("panelId", entity.getId());
                chartPagePanelManageMapper.save(map);
            }
        }
    }

2.原理在Mybatis配置了useGeneratedKeys=“true” keyProperty=“id”

<insert id="save" parameterType="com.centrin.generator.entity.ChartPagePanel" useGeneratedKeys="true" keyProperty="id">
	insert into chart_page_panel
	(
        `parent_id`,
        `position`,
        `name`,
        `create_time`,
        `create_user`,
        `last_modify_time`,
        `last_modify_user`
        )
	values (
		#{parentId},
		#{position},
		#{name},
		NOW(),
		#{createUser},
		NOW(),
		#{lastModifyUser}
		)
  </insert>

你可能感兴趣的:(mybatis)