mybatis 中selectKey 使用

mybatis

selectKey 使用

我们很多时候,主键自增,返回主键值,都是通过注解的方式,现在用selectKey 的使用。

通过selectKey 获取 返回对象的主键值

 <insert id="insert" parameterType="com.longchuang.ronghe.model.Test" >

	<!-- order 执行的顺序,如果为before ,那么就获取不到值了 -->
	<!-- resultType 根据id 的类型,注意数据库中的id 字段必须为自增 -->
    <selectKey keyProperty="id" order="AFTER" resultType="Long">
      SELECT LAST_INSERT_ID() AS ID
    </selectKey>
    insert into t_test (`NAME`,AGE, TEST1,TEST2,TEST3,
      TEST4)
    values (#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER},
      #{test1,jdbcType=VARCHAR},#{test2,jdbcType=VARCHAR},#{test3,jdbcType=VARCHAR},#{test4,jdbcType=VARCHAR})
  </insert>
public interface TestMapper {

    int insert(Test test);
}
@Data
public class Test {

    private Long id;

    private String name;

    private int age;

    private String test1;
    private String test2;
    private String test3;
    private String test4;
}
	@RequestMapping("/test")
    public void test1(){
        Test test = new Test();
        int insert = testMapper.insert(test);
        log.info("data: "+test.getId()); // 能获取id的值
    }
发布了68 篇原创文章 · 获赞 6 · 访问量 6677

猜你喜欢

转载自blog.csdn.net/renguiriyue/article/details/104376670
今日推荐