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的值
}