Mybatis中Insert插入后返回主键id值

    • Mybatis中Insert插入后返回主键id值
      • Mapper的接口:
      • 方法1:
      • 方法2:

Mybatis中Insert插入后返回主键id值

PostgreSQL如何设置自增序列可以点这里:

Mapper的接口:

public interface ThesisMapper {
    int insertSelective(Thesis record);
}

无论什么情况下,interface接口中的int返回的都是影响的条数(可以用来识别成功插入与否),
而返回的自增长主键id值,Mybatis利用反射机制,自动帮我们回填到了Model实体类当中了。我们可以利用model.getId()来获取id值。
(当然,再insert之前,我们用getId()来获取是返回null的)

两种方法:

都是在 mapper.xml文件中

方法1:

    <insert id="insertSelective" parameterType="site.gaoyisheng.pojo.Thesis"
             useGeneratedKeys="true" keyProperty="id">
        insert into public.XXX
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="type != null">
                type,
            if>
            <if test="type != null">
                ....,
            if>
        trim>
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="type != null">
                #{type,jdbcType=VARCHAR},
            if>
            <if test="type != null">
                #{...},
            if>
        trim>
    insert>

其中:
useGeneratedKeys=”true” 表明自增主键值
keyProperty=”id” 用来标识主键colum是’id’

方法2:

    "insertSelective" parameterType="site.gaoyisheng.pojo.Thesis"
             useGeneratedKeys="true" keyProperty="id">
        "int" keyProperty="id" order="BEFORE">
             select currval("自增序列的名称") as id
        

        insert into public.XXX
        "(" suffix=")" suffixOverrides=",">
            <if test="type != null">
                type,
            if>
            <if test="type != null">
                ....,
            if>
        
        "values (" suffix=")" suffixOverrides=",">
            <if test="type != null">
                #{type,jdbcType=VARCHAR},
            if>
            <if test="type != null">
                #{...},
            if>
        
    

其中,

"int" keyProperty="id" order="BEFORE">
             select currval("自增序列的名称") as id

currval(“自增序列的名称”)是PostgreSQL的序列函数,
在MySQL或者oracle中,函数这样用:

MySQL、SQLserver中:

  "_long" keyProperty="id" order="AFTER">
    select @@IDENTITY as id
  

oracle:

  "id" resultType="_long" order="BEFORE">
    select CAST(RANDOM * 100000 as INTEGER) a FROM SYSTEM.SYSDUMMY1
  

附录:


参考资料:

https://blog.csdn.net/timo1160139211/article/details/78193816
https://blog.csdn.net/sinat_30474567/article/details/51395247
https://blog.csdn.net/hardworking0323/article/details/51105136

你可能感兴趣的:(MyBatis,PostgreSQL)