源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Mybatis返回插入主键id的方法

  • 时间:2021-06-13 15:55 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Mybatis返回插入主键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>
[b]PS:Mybatis中insert中返回主键ID的方法[/b] [b]1、XyzMapper.xml[/b]
<insertid=“doSomething"parameterType="map"useGeneratedKeys="true"keyProperty=“yourId">
...
</insert>
<insert id=“doSomething" parameterType=“com.xx.yy.zz.YourClass" useGeneratedKeys="true" keyProperty=“yourId">
...
</insert>
[b]2、XyzMapper.java[/b]
public int doSomething(Map<String, Object> parameters);
or
public int 
doSomething(YourClass c);
[b]3、要在map或c中有一个字段名为yourId,Mybatis会自动把主键值赋给这个字段。[/b]
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);
好了,到此结束,希望对大家有所帮助!
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部