mybatis mysql insert/update 返回自增长主键

关键属性 keyProperty、useGeneratedKeys

官网描述 keyProperty、useGeneratedKeys
keyProperty useGeneratedKeys


代码实例

  • mapper/dao层次代码片段
//这里用了别名"vo"
int insert(@Param("vo") Information information);
  • xml文件代码片段
<!--这里的keyProperty="vo.id",需要主要,如果在mapper/dao层用了别名,需要把别名(比如我这里的`vo`)加上-->
    <insert id="insertInformation" parameterType="com.xxx.commons.entity.Information" keyProperty="vo.id" useGeneratedKeys="true">
        INSERT INTO information (
                    title,
                    create_time,
                    comment_count,
                    praise_count,
                    read_count,
                    url,
                    type,
                    city
                )
                VALUES
                (
                    #{vo.title}         ,
                    #{vo.createTime}    ,
                    #{vo.commentCount}  ,
                    #{vo.praiseCount}   ,
                    #{vo.readCount}     ,
                    #{vo.url}           ,
                    #{vo.type}          ,
                    #{vo.city}
                )
    </insert>
  • service代码片段-结果及保存
#返回的主键值会保存到传入为参数的对象里面
Information information = htmlHandler.parserInformation(htmlRaw);
logger.info("插入前主键值:"+information.getId());
dao.insertInformation(information);
logger.info("插入后主键值:"+information.getId());

# 结果
2018-03-08 17:25:27.709  INFO 10224 --- [   html-fetch-3] c.c.f.s.impl.InformationServiceImpl      : 插入前主键值:0
2018-03-08 17:25:27.724  INFO 10224 --- [   html-fetch-3] c.c.f.s.impl.InformationServiceImpl      : 插入后主键值:101
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容