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

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


利用Mybatis 的 selectKey来获得:

 

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

 

  1. <insert id="addDept" parameterType="com.demo.model.Department" useGeneratedKeys="true" keyProperty="id">  
  2.   insert into department(<include refid="departmentAllField"/>)   
  3.    values(#{departmentId},#{departmentName},#{departmentManagerName},#{companyId});  
  4. </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>

 

posted @ 2021-05-11 14:13  蓝鲸也是鲸  阅读(291)  评论(0编辑  收藏  举报