使用mybatis新增一条数据返回新增数据的id

第一种方法

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

注意事项:

useGeneratedKeys="true" 表示给主键设置自增长,keyProperty="userId" 表示将自增长后的Id赋值给实体类中的userId字段。

parameterType="com.icc.domain.User" 这个属性指向传递的参数实体类

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

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

第二种方式:

    <insert id="insertProduct" parameterType="com.icc.domain.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> 中没有resultType属性,但是<selectKey></selectKey> 标签是有的。

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

可被设置为 BEFORE 或 AFTER。

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

如果设置为 AFTER,那么插入语句执行后执行。

keyProperty="userId" 表示将自增长后的Id赋值给实体类中的userId字段。

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

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

取出方式

Mybatis 执行完插入语句后,自动将自增长值赋值给对象 ProductBean 的属性id。因此,可通过 systemBean 对应的 getter 方法获取!

int count = systemService.insert(productBean);    
        
int id = productBean.getproductId(); //获取到的即为新插入记录的ID 

如果是使用如下序列.nextval来设置id则可以直接通过实体类的get方法获取

<insert id="insertDept" parameterType="SysDept">
        <selectKey keyProperty="deptId" order="BEFORE" resultType="Long">
            select seq_sys_dept.nextval as deptId from DUAL
        </selectKey>
         insert into sys_dept(
             <if test="deptId != null and deptId != 0">dept_id,</if>
             <if test="deptName != null and deptName != ''">dept_name,</if>
             <if test="leader != null and leader != ''">leader</if>
          
         )values(
             <if test="deptId != null and deptId != 0">#{deptId},</if>
             <if test="deptName != null and deptName != ''">#{deptName},</if>
             <if test="leader != null and leader != ''">#{leader}</if>
        
         )
    </insert>
deptMapper.insertDept(dept);
        System.out.println("==============================="+dept.getDeptId());

猜你喜欢

转载自blog.csdn.net/weixin_55823910/article/details/129532516