zoukankan      html  css  js  c++  java
  • 【Mybatis】数据插入数据库时,获取自增主键

    在mybatis的XML文件时,配置useGeneratedKeysKeyProperty属性,且这两个属性不能省略。
    useGeneratedKeys属性,要求数据库本身具备主键自动增长的功能。
    KeyProperty属性,java对象的属性名,也就是要获取的字段。

    1、Mybatis Mapper 中,如下配置。

    <!-- 插入 -->
        <insert id="insert" parameterType="com.liuxs.pojo.OrderPo"
            useGeneratedKeys="true" keyProperty="id">
            insert into T_name
            <trim prefix="(" suffix=")" suffixOverrides=",">
                id,
                <if test="remarks != null">
                    remarks,
                </if>
                <if test="state != null">
                    state,
                </if>
            </trim>
    
            <trim prefix="values (" suffix=")" suffixOverrides=",">
                #{id,jdbcType=BIGINT},
                <if test="remarks != null">
                    #{remarks,jdbcType=VARCHAR},
                </if>
                <if test="state != null">
                    #{state,jdbcType=INTEGER},
                </if>
            </trim>
        </insert>

    2、java代码

    /**
         * 新增备件
         * @param orderPo
         * orderPo中remarks和status用Set方法赋值
         * @return
         */
        @RequestMapping(value = "/insert")
        @ResponseBody
        public Long insert(OrderPo orderPo) {
            Long count = orderService.insert(orderPo);
            System.out.println("共插入" + count + "条记录!"
                    + "
    刚刚插入记录的主键自增长值为:" + orderPo.getId());

    3、另外,还有一种Mybatis配置方式

    <!-- 插入 -->
        <insert id="insert" parameterType="com.liuxs.pojo.OrderPo">
            <selectKey resultType="java.lang.Long" order="AFTER" keyProperty="id">
                  SELECT LAST_INSERT_ID() AS id
            </selectKey>
            insert into T_name
            <trim prefix="(" suffix=")" suffixOverrides=",">
                id,
                <if test="remarks != null">
                    remarks,
                </if>
                <if test="state != null">
                    state,
                </if>
            </trim>
    
            <trim prefix="values (" suffix=")" suffixOverrides=",">
                #{id,jdbcType=BIGINT},
                <if test="remarks != null">
                    #{remarks,jdbcType=VARCHAR},
                </if>
                <if test="state != null">
                    #{state,jdbcType=INTEGER},
                </if>
            </trim>
        </insert>
  • 相关阅读:
    初识ES5、ES6
    WEB前端性能优化之三——JavaScript优化
    Web前端浏览器兼容问题
    HTML5新特性
    WEB前端性能优化之二——css优化
    WEB前端性能优化之一——网页级优化
    CSS的一些案例和坑
    bootstrap插件--select2.js--一个基于jQuery的替换框
    boostrap插件---typeahead.js---输入提示下拉菜单
    border-radius:50%,在安卓上存在兼容问题
  • 原文地址:https://www.cnblogs.com/liuxs13/p/7794771.html
Copyright © 2011-2022 走看看