Mybatis -- insert 语句

mybatis 插入

  • mybatis新增数据
<insert id="insert">
		insert into sys_user(id,user_name,user_password,user_email,user_info,head_img,create_time)
		values(#{id},#{userName},#{userPassword},#{userEmail},#{userInfo},#{headImg},#{createTime})
insert>
  • mybatis 新增返回主键
useGeneratedKeys 设置为true之后,mybatis会使用JDBC的getGeneratedKeys 方法取出来由数据库内部生成的主键。
获得到主键后将其赋值给keyProperty配置的id属性。当需要设置多个属性时,使用逗号隔开,这种情况下通常还需要设置
keyColumn属性,按顺序指定数据库的列,这里列的值会和keyProperty配置的属性一一对应。由于要使用数据库返回的主键值,
所以SQL上下两部分的列中去掉了id列和对应的#{id}列

直接从对象属性中获取id

<insert id="insert2" useGeneratedKeys="true" keyProperty="id">
		insert into sys_user(id,user_name,user_password,user_email,user_info,head_img,create_time)
		values(
			#{id},#{userName},#{userPassword},
			#{userEmail},#{userInfo},
			#{headImg, jdbcType=BLOB},
			#{createTime,jdbcType=TIMESTAMP}
		)
insert>
  • selectKey 获取主键
mysql:
<selectKey keyColumn="id" resultType="Long" keyProperty="id" order="AFTER">
			select last_insert_id()
selectKey>

oracle:
<selectKey keyColumn="id" resultType="Long" keyProperty="id" order="BEFORE">
			select SEQ_ID.nextval from dual
selectKey>

sqlserver:
select scope_identity()

<insert id="insert3">
		insert into sys_user(id,user_name,user_password,user_email,user_info,head_img,create_time)
		values(
			#{id},#{userName},#{userPassword},
			#{userEmail},#{userInfo},
			#{headImg, jdbcType=BLOB},
			#{createTime,jdbcType=TIMESTAMP}
		)
		<selectKey keyColumn="id" resultType="Long" keyProperty="id" order="AFTER">
			select last_insert_id()
		selectKey>
insert>
  • 注解@Insert
    • 插入
      	@Insert({ "insert into sys_role(id,role_name,enabled,create_by,create_time)"
      		+ "values(#{id},#{roleName},#{enabled},#{createBy},#{createTime})" })
      	void insert1(SysRole sysRole);
      
    • 返回自增主键
      	@Insert({ "insert into sys_role(role_name,enabled,create_by,create_time)"
      		+ "values(#{roleName},#{enabled},#{createBy},#{createTime})" })
      	@Options(useGeneratedKeys=true,keyProperty="id")
      	void insert2(SysRole sysRole);
      
    • 返回非自增主键
      	@Insert({ "insert into sys_role(role_name,enabled,create_by,create_time)"
      		+ "values(#{roleName},#{enabled},#{createBy},#{createTime})" })
      	@SelectKey(statement = "select last_insert_id()",
      				keyProperty = "id",
      				resultType = Long.class,
      				before = false
      			)
      	void insert3(SysRole sysRole);
      

你可能感兴趣的:(mybatis)