mybaits返回插入成功后的自增值

mybaits返回插入成功后的自增值

在项目中,我们经常遇到这样的情况:insert语句成功后,需要自增的id值,这个时候,我们可以通过mybatis的 useGeneratedKeys 来实现,具体如下:

   <!--新增巡检预案-->
    <insert id="insertVideoFormPolling" useGeneratedKeys="true" keyProperty="pollingPlan.pollingPlanId" parameterType="com.unisits.zngkpt.data.pollingmandata.pojo.PollingPlan" >
      INSERT INTO polling_plan(polling_plan_type,unit_id,polling_plan_name,polling_plan_desc)
      VALUES (1,${pollingPlan.unitId},#{pollingPlan.pollingPlanName},#{pollingPlan.pollingPlanDesc})
    </insert>

在这里,useGeneratedKeys 代表这个表的id是自增的,keyProperty属性指定,哪列是自增的,那么怎么获取自增的id呢?

public void addVideoFormPolling(){
PollingPlan pp = new PollingPlan();
pp.setPollingPlanName("test23");
pp.setUnitId(1000);
pp.setPollingPlanDesc("test");
int result = pollingVideoDao.insertVideoFormPolling(pp);
System.out.println(pp.getPollingPlanId()+"--"+result);
}

而这里的 pp.getPollingPlanId() 就是获取的返回值的id

原文地址:https://www.cnblogs.com/ningheshutong/p/8126641.html