Mybatis主键回填

  1. 接口
int insert(Department record);
  1. mapper.xml文件中
<insert id="insert" parameterType="com.example.hrservice.hr.model.Department"  useGeneratedKeys="true" keyProperty="id">
    insert into department (id, name, parentId,  depPath, enabled, isParent)
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{parentId,jdbcType=INTEGER}, 
      #{depPath,jdbcType=VARCHAR}, #{enabled,jdbcType=BIT}, #{isParent,jdbcType=BIT})
  </insert>

需要加上useGeneratedKeys="true" keyProperty="id"
这样我们传入的record对象无需设置id字段,Mybatis会自动进行设置处理,插入成功后id字段会回填到record对象中。
mybatis官方地址:https://mybatis.org/mybatis-3/zh/sqlmap-xml.html#select

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容