Mybatis returns the method for inserting the main key id
- 2020-06-23 00:24:50
- OfStack
Configure useGeneratedKeys in xml's xml file
And keyProperty just return Id
<insert id="insertObject" useGeneratedKeys="true" keyProperty="id" parameterType="www.change.tm.model.Orders" >
insert into orders
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="number!=null">
OrderNumber,
</if>
<if test="orderTime!=null">
orderTime,
</if>
</trim>
values
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="number!=null">
#{number},
</if>
<if test="orderTime!=null">
#{orderTime},
</if>
</trim>
</insert>
PS: The method in insert in Mybatis that returns the primary key ID
1, XyzMapper. xml
<insertid= " doSomething"parameterType="map"useGeneratedKeys="true"keyProperty= " yourId">
...
</insert>
or
<insert id= " doSomething" parameterType= " com.xx.yy.zz.YourClass" useGeneratedKeys="true" keyProperty= " yourId">
...
</insert>
2, XyzMapper java
public int doSomething(Map<String, Object> parameters);
or
public int
doSomething(YourClass c);
3. To have a field named yourId in map or c, Mybatis will automatically assign the primary key value to this field.
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put( " yourId " , 1234);
...
mapper.doSomething(parameters);
System.out.println( " id of the field that is primary key " + parameters.get( " yourId"));
or
YourClass c = new YourClass();
...
mapper.doSomething(c);
System.out.println( " id of the field that is primary key " + c.yourId);
Well, this is the end, I hope to help you!