Mybatis返回插入主鍵id的方法。本站提示廣大學習愛好者:(Mybatis返回插入主鍵id的方法)文章只能為提供參考,不一定能成為您想要的結果。以下是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>
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);
好了,到此結束,希望對大家有所幫助!