Mybatis返回插入主键id的方法

2025-05-29 0 18

在mapper的xml文件中配置 useGeneratedKeys

以及 keyProperty 返回Id即可

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20
<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

?

1

2

3
<insertid=“doSomething"parameterType="map"useGeneratedKeys="true"keyProperty=“yourId">

...

</insert>

?

1

2

3
<insert id=“doSomething" parameterType=“com.xx.yy.zz.YourClass" useGeneratedKeys="true" keyProperty=“yourId">

...

</insert>

2、XyzMapper.java

?

1

2

3

4
public int doSomething(Map<String, Object> parameters);

or

public int

doSomething(YourClass c);

3、要在map或c中有一个字段名为yourId,Mybatis会自动把主键值赋给这个字段。

?

1

2

3

4

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

?

1

2

3

4
YourClass c = new YourClass();

...

mapper.doSomething(c);

System.out.println(“id of the field that is primary key” + c.yourId);

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

原文链接:http://blog.csdn.net/mr_yarnell/article/details/70146838

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Mybatis返回插入主键id的方法 https://www.kuaiidc.com/117716.html

相关文章

发表评论
暂无评论