mybatis在MySQL中插入數據並返回主鍵

1、使用xml方式

     方式一:

<insert id="addUserByXml" parameterType="user">
        <selectKey keyProperty="id" keyColumn="id" order="AFTER" resultType="java.lang.Integer">
            select last_insert_id()
        </selectKey>
        insert into t_user(username,password,birthday,sex,address)
        values (#{username},#{password},#{birthday},#{sex},#{address})
</insert>

    方式二:

<insert id="addUserByXml" parameterType="user" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
        insert into t_user(username,password,birthday,sex,address)
        values (#{username},#{password},#{birthday},#{sex},#{address})
</insert>

2、使用註解方式

    方式一:

@InsertProvider(type = UserProvider.class,method = "insertUser")
@SelectKey(keyColumn = "id",keyProperty = "id",before = false,resultType = Integer.class,statement = "select last_insert_id()")
Integer addUser(User user);

   方式二:

@InsertProvider(type = UserProvider.class,method = "insertUser")
@Options(useGeneratedKeys = true,keyProperty = "id",keyColumn = "id")
Integer addUser(User user);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章