欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

mybatis在MySQL中插入数据并返回主键

程序员文章站 2022-06-02 15:53:02
...

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);

 

相关标签: 获取主键