MyBatis Insert插入数据返回主键的几种模式支持,包括@Insert注解,mapper.xml sql语句。
mybatis insert插入数据返回id前置条件
id必须是数字类型,且设置了自增长
@Insert(insert into user values(#{id},#{name},#{age}) @SelectKey(statement = "select last_insert_id() from dual", before = false, resultType = Interger.class, keyColumn = "id", keyProperty = "user.id") int add(@Param("user") User user);
在mapper层用注解的方式,用@SelectKey注解
@SelectKey里面属性含义:
该方式关键点:@SelectKey 注解的配置和使用
该方法理论和上方注解相似,以mapper xml方式实现,参考:
<insert id="insert" parameterType="com.***.User"> <selectKey resultType="java.lang.Integer" order="AFTER" keyProperty="user.id"> select LAST_INSERT_ID() </selectKey> insert into user <trim prefix="(" suffix=")" suffixOverrides=","> <if test="user.id != -1"> id, </if> <if test="user.name!= null and user.name!=''"> user, </if> <if test="user.age!= null"> age, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="attachment.id != -1"> #{user.id,jdbcType=BIGINT}, </if> <if test="user.name!= null and user.name!=''"> #{user.name,jdbcType=VARCHAR}, </if> <if test="user.age!= null"> #{user.age,jdbcType=INTEGER}, </if> </trim> </insert>
该方式关键点:多了个<selectKey>查询
<insert id="insert" parameterType="com.***.User" useGeneratedKeys="true" keyProperty="user.id" keyColumn="id"> insert into user <trim prefix="(" suffix=")" suffixOverrides=","> <if test="user.id != -1"> id, </if> <if test="user.name!= null and user.name!=''"> name, </if> <if test="user.age!= null"> age, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="user.id != -1"> #{user.id,jdbcType=BIGINT}, </if> <if test="user.name!= null and user.name!=''"> #{user.name,jdbcType=VARCHAR}, </if> <if test="user.age!= null"> #{user.age,jdbcType=INTEGER}, </if> </trim> </insert>
该方式关键点:useGeneratedKeys 配置为true,keyProperty指定自增长主键字段名称
搞定
https://www.leftso.com/article/2404161028052869.html