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

Mybatis返回插入主键id的方法

程序员文章站 2024-03-02 10:59:40
在mapper的xml文件中配置  usegeneratedkeys 以及 keyproperty 返回id即可

在mapper的xml文件中配置  usegeneratedkeys

以及 keyproperty 返回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:mybatis中insert中返回主键id的方法

1、xyzmapper.xml

<insertid=“dosomething"parametertype="map"usegeneratedkeys="true"keyproperty=“yourid">
...
</insert>

<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、要在map或c中有一个字段名为yourid,mybatis会自动把主键值赋给这个字段。

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

yourclass c = new yourclass();
...
mapper.dosomething(c);
system.out.println(“id of the field that is primary key” + c.yourid);

好了,到此结束,希望对大家有所帮助!