注: MySQL中可直接使用 uuid() 函数生成uuid
<!-- 新增 -->
<insert id="insert" parameterType="com.xxx.xxx.MiniPollingImage" useGeneratedKeys="true" keyProperty="id">
<selectKey keyColumn="id" keyProperty="id" resultType="string" order="BEFORE">
<!-- selectKey 标签表示子查询中主键的提取问题
keyColumn:表示查询语句返回结果的列名
keyProperty:表示对应的 domain 对象(指 parameterType 指定的对象)中需要被赋值的属性,一般是主键
相当于java中设置实体类属性一样
order="BEFORE:表示在插入语句之前执行
resultType="int":表示返回值得类型为int类型 -->
-- SelectKey需要注意order属性,像MySQL一类支持自动增长类型的数据库中,order需要设置为AFTER才会取到正确的值,像Oracle这样取序列的情况,需要设置为BEFORE
-- 在上面示例的insert用法中,就是order属性设置成了BEFORE才导致自增属性没有生效。改成AFTER后,主键就开始自增了
select replace(uuid(), '-', '') as id from dual
</selectKey>
INSERT INTO mini_polling_image(
id,
image_url,
type,
product_id,
sort,
created_time,
created_by,
last_update_by,
last_update_time
) VALUES (
#{id},
#{imageUrl},
#{type},
#{productId},
#{sort},
#{createdTime},
#{createdBy},
#{lastUpdateBy},
#{lastUpdateTime}
)
</insert>
注意:
在做关联表插入操作时,需要根据主表的 主键 id 作详情表的属性值,最笨的方法就是,先插入主表,然后通过查询返回刚刚插入的主键id,继续添加详情表数据
新方案:
使用 keyProperty和useGeneratedKeys 属性
useGeneratedKeys参数只针对 insert 语句生效,默认为 false。当设置为 true 时,表示如果插入的表以自增列为主键,则允许 JDBC 支持自动生成主键(在上例中即使用selectKey生成的主键),并可将自动生成的主键返回。
具体用法:
useGeneratedKeys="true" keyProperty="对应的主键的对象"
上面的SQL语句后如下:
insert!selectKey - ==> Preparing: select replace(uuid(), '-', '') as id from dual
insert!selectKey - ==> Parameters:
insert!selectKey - <== otal: 1
JDPollingImageDao.insert - ==> Preparing: INSERT INTO mini_polling_image( id, image_url, type, product_id, sort, created_time, created_by, last_update_by, last_update_time ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ? )
JDPollingImageDao.insert - ==> Parameters: b857ca5a85df11e98058c70bde3c8e14(String), https://img14.360buyimg.com/n1/jfs/t1/40230/29/6518/60461/5cd12bc8E19b67178/cd0de44a4c68b35c.jpg(String), 1(String), 12797839349(String), 1(Integer), 2019-06-03 17:12:44.689(Timestamp), admin(String), null, null
JDPollingImageDao.insert - <== Updates: 1