在mybatis的XML文件时,配置useGeneratedKeys和KeyProperty属性,且这两个属性不能省略。
useGeneratedKeys属性,要求数据库本身具备主键自动增长的功能。
KeyProperty属性,java对象的属性名,也就是要获取的字段。
1、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>
2、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 + "条记录!" + " 刚刚插入记录的主键自增长值为:" + orderPo.getId());
3、另外,还有一种Mybatis配置方式
<!-- 插入 --> <insert id="insert" parameterType="com.liuxs.pojo.OrderPo"> <selectKey resultType="java.lang.Long" order="AFTER" keyProperty="id"> SELECT LAST_INSERT_ID() AS id </selectKey> 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>