0
点赞
收藏
分享

微信扫一扫

mybatis 添加一条新数据并返回此数据的ID(主键)

凉夜lrs 2022-02-28 阅读 70

利用Mybatis 的 selectKey来获得:

方法一:

<!-- 添加部门 返回部门ID -->  
<insert id="addDept" parameterType="com.demo.model.Department" keyProperty="id">  
    <selectKey keyProperty='id' resultType='int' order='AFTER'  >  
        select LAST_INSERT_ID();  
    </selectKey>  
     insert into department(<include refid="departmentAllField"/>)   
        values(#{departmentId},#{departmentName},#{departmentManagerName},#{companyId});  
 </insert> 

方法二:

<insert id="addDept" parameterType="com.demo.model.Department" useGeneratedKeys="true" keyProperty="id">  
  insert into department(<include refid="departmentAllField"/>)   
   values(#{departmentId},#{departmentName},#{departmentManagerName},#{companyId});  
</insert>

注意:insert 标签中的 keyProperty 和 selectKey标签块中的 LAET_INSERT_ID() ,另外 order属性 对于 oracl为 BEFORE; mysql为AFTER

方法三:

<insert id="insert" keyColumn="id" keyProperty="id" parameterType="com.edu.archive.business.domain.grade.pojo.model.ApplicationRecord" useGeneratedKeys="true">

  insert into bj_application_record (parent_id, class_no, student_name, 
    kinsfolk_relation, `status`, refuse_remark, 
    create_time, update_time, version
    )
  values (#{parentId,jdbcType=INTEGER}, #{classNo,jdbcType=VARCHAR}, #{studentName,jdbcType=VARCHAR}, 
    #{kinsfolkRelation,jdbcType=VARCHAR}, #{status,jdbcType=TINYINT}, #{refuseRemark,jdbcType=VARCHAR}, 
    #{createTime,jdbcType=TIMESTAMP}, #{updateTime,jdbcType=TIMESTAMP}, #{version,jdbcType=INTEGER}
    )
</insert>

mybatis 添加一条新数据并返回此数据的ID(主键) - 蓝鲸也是鲸 - 博客园

举报

相关推荐

0 条评论