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>
  • 相关阅读:
    deepin v20装机后python配置
    lotus命令详解
    Lotus 客户端命令集合
    在Windows 7或Server 2008 R2上安装更新时提示0x80092004错误的解决方案
    Delphi:如何将列表作为参数传递给SQL查询?
    delphi Ado 执行带有冒号字符语句的处理。
    SQLite与Delphi XE4 (一)
    delphi在TMemo中实现高亮文字
    Delphi中用beep函数拼出节奏和歌曲
    在oracle中插入数据报错:ORA-00984列在此处不允许
  • 原文地址:https://www.cnblogs.com/liuxs13/p/7794771.html
Copyright © 2011-2022 走看看