【Mybatis】資料插入資料庫時,獲取自增主鍵
阿新 • • 發佈:2019-02-09
在mybatis的XML檔案時,配置useGeneratedKeys和KeyProperty屬性,且這兩個屬性不能省略。
useGeneratedKeys屬性,要求資料庫本身具備主鍵自動增長的功能。
KeyProperty屬性,java物件的屬性名,也就是要獲取的欄位。
- 在Mybatis Mapper 中,如下配置。
<!-- 插入 -->
<insert id="insert" parameterType="com.liuxs.pojo.OrderPo"
useGeneratedKeys="true" keyProperty="id" >
insert into T_name
<trim prefix="(" suffix=")" suffixOverrides=",">
id,
<if test="remarks != null">
remarks,
</if>
<if test="state != null">
state,
</if>
</trim >
<trim prefix="values (" suffix=")" suffixOverrides=",">
#{id,jdbcType=BIGINT},
<if test="remarks != null">
#{remarks,jdbcType=VARCHAR},
</if>
<if test="state != null">
#{state,jdbcType=INTEGER},
</if >
</trim>
</insert>
- java配置如下
/**
* 新增備件
* @param orderPo
* orderPo中remarks和status用Set方法賦值
* @return
*/
@RequestMapping(value = "/insert")
@ResponseBody
public Long insert(OrderPo orderPo) {
Long count = orderService.insert(orderPo);
System.out.println("共插入" + count + "條記錄!"
+ "\n剛剛插入記錄的主鍵自增長值為:" + orderPo.getId());