• mybatis返回主键


    最近偷懒

    把以前落下的补上

    第一种方式:

    在实体类的映射文件 "*Mapper.xml" 这样写:

    <insert id="insertAndGetId" useGeneratedKeys="true" keyProperty="userId" parameterType="com.lyf.pojo.User">
        insert into user(userName,password,comment)
        values(#{userName},#{password},#{comment})
    </insert>

    参数解析:

    useGeneratedKeys="true" 表示给主键设置自增长
    keyProperty="userId"  表示将自增长后的Id赋值给实体类中的userId字段。
    parameterType="com.lyf.pojo.User" 这个属性指向传递的参数实体类

    这里提醒下,<insert></insert> 中没有resultType属性,不要乱加。

    实体类中uerId 要有getter() and setter(); 方法

    第二种方式:

    同样在实体类的映射文件 "*Mapper.xml" 但是要这样写:

    复制代码
        <!-- 插入一个商品 -->
        <insert id="insertProduct" parameterType="com.lyf.pojo.ProductBean" >
           <selectKey resultType="java.lang.Long" order="AFTER" keyProperty="productId">
              SELECT LAST_INSERT_ID()
          </selectKey>
            INSERT INTO t_product(productName,productDesrcible,merchantId)values(#{productName},#{productDesrcible},#{merchantId});
        </insert>
    复制代码

    参数解析: 

    <insert></insert> 中没有resultType属性,但是<selectKey></selectKey> 标签是有的。

    order="AFTER" 表示先执行插入语句,之后再执行查询语句。

    可被设置为 BEFORE 或 AFTER。

    如果设置为 BEFORE,那么它会首先选择主键,设置 keyProperty 然后执行插入语句。

    如果设置为 AFTER,那么先执行插入语句,然后是 selectKey 元素-这和如 Oracle 数据库相似,可以在插入语句中嵌入序列调用
    keyProperty="userId"  表示将自增长后的Id赋值给实体类中的userId字段。

    SELECT LAST_INSERT_ID() 表示MySQL语法中查询出刚刚插入的记录自增长Id.

    实体类中uerId 要有getter() and setter(); 方法
    
    
  • 相关阅读:
    onTouchEvent的参数详解
    test
    List泛型自定义排序
    unity3d camera.culling mask
    云计算实验一
    软件设计——职责链模式之审批处理
    sqlserver配置sa用户
    软件设计——模板方法模式之对数据库的操作
    flask入门
    课程总结+申请加分
  • 原文地址:https://www.cnblogs.com/a-small-lyf/p/10324822.html
Copyright © 2020-2023  润新知