MyBatis的xml文件中主键操作

注: 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需要注意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

你可能感兴趣的:(java,MyBatis,uuid(),selectKey)