1. 程式人生 > >mybatis 新增返回自增的id值

mybatis 新增返回自增的id值

簡單的介紹一下吧

1-實體類

public class Department {
        private Integer id;
        private String name;
        private Integer parentId;
        private String logoName;
        private String logoPath;
        private String introduce;
        private String oid;
       // get set  省略
}
2-Dao類
 public void add(Department department) {
        try {
            mapper.add(department);
            System.out.println(department.getId());
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

    }
返回 id 有兩種方法,其中一種是使用註解,返回的id會自動複製在 Department 實體類的id屬性中

3.1 註解(Interface)

@Insert("INSERT INTO department(`name`,introduce,parent_id,org_id)\n" +
        "            VALUES (\n" +
        "            #{department.name,jdbcType = VARCHAR},\n" +
        "            #{department.introduce,jdbcType = VARCHAR},\n" +
        "            #{department.parentId,jdbcType = VARCHAR},\n" +
        "            #{department.oid,jdbcType = VARCHAR}\n" +
        "            )")
      @Options(useGeneratedKeys = true, keyProperty = "department.id",keyColumn = "id")
        void add(@Param("department") Department department);
3.2 Mapper.xml 
void add(@Param("department") Department department);
    <insert id="add" useGeneratedKeys="true" keyProperty="department.id" parameterType="mp.module.daomain.department.Department">
        <!--<selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="department.id">-->
            <!--select last_insert_rowid() as id-->
        <!--</selectKey>-->
        INSERT INTO department(`name`,introduce,parent_id,org_id)
            VALUES (
            #{department.name,jdbcType = VARCHAR},
            #{department.introduce,jdbcType = VARCHAR},
            #{department.parentId,jdbcType = VARCHAR},
            #{department.oid,jdbcType = VARCHAR}
            )
    </insert>


4 測試結果均可顯示