在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);
好了,到此结束,希望对大家有所帮助!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。