Mybatis插入记录并返回MySQL自增主键

mapper

 Integer insertConfigAndGetId(CrawlerConfig config);

xml

    <insert id="insertConfigAndGetId" parameterType="com.suning.epp.fmasosadmin.dmo.CrawlerConfig">
        <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
            select LAST_INSERT_ID() as id
        </selectKey>
        insert into
        T_CRAWLER_CONFIG(START_URL,PROCESSOR,PIPELINE_NAME,THREAD_NAME,RETRY_TIMES,SLEEP_TIME,CHARSET,HEADERS)
        values
        (#{startUrl},#{processor},#{pipelineName},#{threadNum},#{retryTimes},#{sleepTime},#{charset},#{headers})
    </insert>

参数说明:

resultType:返回的主键类型

order:这可以被设置为 BEFORE 或 AFTER。如果设置为 BEFORE,那么它会首先选择主键,设置 keyProperty 然后执行插入语句。

如果设置为 AFTER,那么先执行插入语句,然后执行 selectKey 元素 。

keyProperty:selectKey 语句结果应该被设置的目标属性(对应参数中的主键的属性名),keyproperty将查询到的主键值设置到parameterType相对应的哪个属性

注意:

取返回的主键名不能用

Integer cid = crawlConfigMapper.insertConfigAndGetId(config);

这样取到的值是插入影响的条数,而不是刚插入记录的主键值!!!

刚插入记录的主键值从刚插入记录的实体参数中取:

crawlConfigMapper.insertConfigAndGetId(config);
// 刚保存记录的主键值
Integer cid = config.getId();

需要注意:主从同步时,可能会导致查询不到id的问题,建议一直从主库中查询



原文地址:https://www.cnblogs.com/yangyongjie/p/10719529.html