zoukankan      html  css  js  c++  java
  • MyBatis插入时获取自增长主键

    在某些场景下,我们需要使用mybatis返回生成的主键值。Mybatis在insert和update标签中就提供了这种功能。

    方法1:

    <insert id=”indetifyId”  useGeneratedKeys=”true” keyProperty=”id” keyColumn="id">
    
    </insert>
    • useGeneratedKeys: 是否自动生成主键,默认false
    • keyProperty :返回的主键值赋给哪个属性
    • keyColumn: 数据库中的自增主键的列名,默认是数据库表的第一列。当主键列不是表中的第一列的时候需要设置,PostgreSQL必须设置。
    • 主键自动生成,取决于数据库是否支持自增主键。实际上当设置了useGeneratedKeys=“true”,Mybatis会调用JDBC的getGeneratedKeys方法,并将获取的主键值赋值给keyProperty 指定的属性。

    方法2:

        <insert id="insertCustomer" parameterType="cn.rayfoo.bean.Customer">
            <!--
            获取插入的最后一个id
            keyColumn 哪个字段时自增长id
            keyProperty 将值保存到parameterType对应bean对象的那个属性中
            resultType 该属性的类型
            order 执行sql后赋值还是执行之前赋值
            -->
            <selectKey keyColumn="cust_id" keyProperty="cust_id" resultType="Integer" order="AFTER">
                select last_insert_id()
            </selectKey>
            insert into customer(cust_name,cust_profession,cust_phone,email)
            values(#{cust_name},#{cust_profession},#{cust_phone},#{email});
        </insert>
  • 相关阅读:
    ●BZOJ 2752 [HAOI2012]高速公路(road)
    ●UVA 11021 tunnello
    ●POJ 2794 Double Patience
    【51Nod1555】布丁怪
    【LG1600】[NOIP2016]天天爱跑步
    【LG5171】Earthquake
    【LG4437】[HNOI/AHOI2018]排列
    【CF1097F】Alex and a TV Show
    【51Nod 1769】Clarke and math2
    【LG5330】[SNOI2019]数论
  • 原文地址:https://www.cnblogs.com/zhangruifeng/p/12263426.html
Copyright © 2011-2022 走看看