一, mybatis 对应的特定表 (Customer) 的配置
1, 代码
<insert id="insertSelective" parameterType="Customer"
keyProperty="customerid" useGeneratedKeys="true" >
insert into im_customer
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="customercode != null" >
CustomerCode,
</if>
<if test="customername != null" >
CustomerName,
</if>
<if test="customerlocation != null" >
CustomerLocation,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="customercode != null" >
#{customercode,jdbcType=VARCHAR},
</if>
<if test="customername != null" >
#{customername,jdbcType=VARCHAR},
</if>
<if test="customerlocation != null" >
#{customerlocation,jdbcType=VARCHAR},
</if>
</trim>
</insert>
2, 解释
keyProperty是Java对象的属性,其对应于数据库中指定表的主键字段;
useGeneratedKeys 参数只针对 insert 语句生效,默认为 false。
① keyProperty 和 useGeneratedKeys 一起使用
如果你的数据库支持自动生成主键的字段(比如 MySQL 和 SQL Server),那么你可以设置 useGeneratedKeys=”true”,然后再把 keyProperty 设置到目标属性上就OK了。
<insert id="insertAuthor" useGeneratedKeys="true"
keyProperty="id">
insert into Author (username,password,email,bio)
values (#{username},#{password},#{email},#{bio})
</insert>
② 只使用keyProperty,不使用useGeneratedKeys,就需要配合<selectKey >使用
<insert id="insertAuthor">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
select CAST(RANDOM()*1000000 as INTEGER) a from SYSIBM.SYSDUMMY1
</selectKey>
insert into Author
(id, username, password, email,bio, favourite_section)
values
(#{id}, #{username}, #{password}, #{email}, #{bio}, #{favouriteSection,jdbcType=VARCHAR})
</insert>
二, 执行
1, 这样配置完了之后,运行程序并不能想象那样就成功了,第一次插入的时候必须要在mysql数据库里执行一下主键自增的语句,才能如愿以偿的新增成功,
alter table student modify studnet_id integer auto_increment ,student表名,student_id 是主键。
2,mysql设置ID增值起始值的语句:
alter table student AUTO_INCREMENT=1000
- useGenerateKey:开启返回自增列
- KeyProperty:返回自增列,对象对应的属性,
- 自增列值获取:自增主键会映射到对象对应的属性中