MyBatis the interface that returns the primary Key ID value mapper After Insert insertion: Method 1: Method 2:
return primary Key ID value after insert insertion in MyBatis
PostgreSQL how to set up a self-adding sequence can point here: Mapper Interface:
Public interface Thesismapper {
int insertselective (thesis record);
}
In any case, the int in the interface interface returns the number of affected bars (which can be used to identify successful inserts).
And the return of the MyBatis primary key ID value, the use of reflection mechanism, automatically help us backfill into the model entity class. We can use Model.getid () to get the ID value.
(Of course, before we insert, we use GetID () to get the return null)
Two ways:
In the Mapper.xml file, Method 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>
which
usegeneratedkeys= "True" indicates the value of the self-added primary key
keyproperty= "id" is used to identify the primary key colum is ' ID ' Method 2:
<insert id= "insertselective" parametertype= "site.gaoyisheng.pojo.Thesis"
usegeneratedkeys= "true" keyproperty= "id" >
<selectkey resulttype= "int" keyproperty= "id" order= "before" >
select Currval (" Name of the self-added sequence ") as ID
</selectKey>
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>
which
<selectkey resulttype= "int" keyproperty= "id" order= "before" >
select Currval ("Name of self-added sequence") as ID
</ Selectkey>
Currval (the name of the "self-added sequence") is a sequence function of the PostgreSQL,
In MySQL or Oracle, functions are used in this way:
MySQL, SQL Server:
<selectkey resulttype= "_long" keyproperty= "id" order= "after" >
SELECT @ @IDENTITY as ID
</selectkey >
Oracle
<selectkey keyproperty= "id" resulttype= "_long" order= "before" >
select CAST (RANDOM * 100000 as INTEGER) a from S Ystem. SYSDUMMY1
</selectKey>
Appendix:
Resources:
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