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


猜你喜欢

转载自blog.csdn.net/fxj0720/article/details/80733334