第一種方法
<insert id="insertAndGetId" useGeneratedKeys="true" keyProperty="userId" parameterType="com.icc.domain.User">
insert into user(userName,password)
values(#{userName},#{password})
</insert>
注意事項(xiàng):
useGeneratedKeys="true" 表示給主鍵設(shè)置自增長(zhǎng),keyProperty="userId" 表示將自增長(zhǎng)后的Id賦值給實(shí)體類中的userId字段。
parameterType="com.icc.domain.User" 這個(gè)屬性指向傳遞的參數(shù)實(shí)體類
這里提醒下,<insert></insert> 中沒(méi)有resultType屬性,不要亂加。
實(shí)體類中uerId 要有g(shù)etter() and setter(); 方法
第二種方式:
<insert id="insertProduct" parameterType="com.icc.domain.ProductBean" >
<selectKey resultType="java.lang.Long" order="AFTER" keyProperty="productId">
SELECT LAST_INSERT_ID()
</selectKey>
INSERT INTO t_product(productName,productDesrcible,merchantId)values(#{productName},#{productDesrcible},#{merchantId});
注意事項(xiàng):
<insert></insert> 中沒(méi)有resultType屬性,但是<selectKey></selectKey> 標(biāo)簽是有的。
order="AFTER" 表示先執(zhí)行插入語(yǔ)句,之后再執(zhí)行查詢語(yǔ)句。
可被設(shè)置為 BEFORE 或 AFTER。
如果設(shè)置為 BEFORE,那么它會(huì)首先選擇主鍵,設(shè)置 keyProperty 它會(huì)在插入語(yǔ)句前執(zhí)行。
如果設(shè)置為 AFTER,那么插入語(yǔ)句執(zhí)行后執(zhí)行。
keyProperty="userId" 表示將自增長(zhǎng)后的Id賦值給實(shí)體類中的userId字段。
SELECT LAST_INSERT_ID() 表示MySQL語(yǔ)法中查詢出剛剛插入的記錄自增長(zhǎng)Id.
實(shí)體類中uerId 要有g(shù)etter() and setter(); 方法
取出方式
Mybatis 執(zhí)行完插入語(yǔ)句后,自動(dòng)將自增長(zhǎng)值賦值給對(duì)象 ProductBean 的屬性id。因此,可通過(guò) systemBean 對(duì)應(yīng)的 getter 方法獲??!文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-633141.html
int count = systemService.insert(productBean);
int id = productBean.getproductId(); //獲取到的即為新插入記錄的ID
如果是使用如下序列.nextval來(lái)設(shè)置id則可以直接通過(guò)實(shí)體類的get方法獲取文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-633141.html
<insert id="insertDept" parameterType="SysDept">
<selectKey keyProperty="deptId" order="BEFORE" resultType="Long">
select seq_sys_dept.nextval as deptId from DUAL
</selectKey>
insert into sys_dept(
<if test="deptId != null and deptId != 0">dept_id,</if>
<if test="deptName != null and deptName != ''">dept_name,</if>
<if test="leader != null and leader != ''">leader</if>
)values(
<if test="deptId != null and deptId != 0">#{deptId},</if>
<if test="deptName != null and deptName != ''">#{deptName},</if>
<if test="leader != null and leader != ''">#{leader}</if>
)
</insert>
deptMapper.insertDept(dept);
System.out.println("==============================="+dept.getDeptId());
到了這里,關(guān)于使用mybatis新增一條數(shù)據(jù)返回新增數(shù)據(jù)的id的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!