Mybatis插入数据行ID生成策略

倾然丶 夕夏残阳落幕 提交于 2019-12-17 13:59:11

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

Oracle:

<insert id="insert" parameterType="vo.Category">

<selectKey resultType="java.lang.Short" order="BEFORE" keyProperty="id">

SELECT SEQ_TEST.NEXTVAL FROM DUAL

</selectKey>

insert into category (id,name_zh, parent_id,

show_order, delete_status, description

)

values (
#{id,jdbcType=NUMBER},

#{nameZh,jdbcType=VARCHAR},

#{parentId,jdbcType=NUMBER},

#{showOrder,jdbcType=NUMBER},

#{deleteStatus,jdbcType=NUMBER},

#{description,jdbcType=VARCHAR}

)

</insert>

MySQL:

针对自增主键的表,在插入时不需要主键,而是在插入过程自动获取一个自增的主键,比如MySQL,可以采用如下两种配置方式:
 

<insert id="insert" parameterType="vo.Category" useGeneratedKeys="true" keyProperty="id">

insert into category (id,name_zh, parent_id,

show_order, delete_status, description

)

values (
#{id,jdbcType=INTEGER},

#{nameZh,jdbcType=VARCHAR},

#{parentId,jdbcType=INTEGER},

#{showOrder,jdbcType=INTEGER},

#{deleteStatus,jdbcType=BIT},

#{description,jdbcType=VARCHAR}

)

</insert>


 

<insert id=" insert " parameterType="vo.Category">

<selectKey resultType="java.lang.Short" order="AFTER" keyProperty="id">

SELECT LAST_INSERT_ID() AS id

</selectKey>

insert into category (id,name_zh, parent_id,

show_order, delete_status, description

)

values (
#{id,jdbcType=INTEGER},

#{nameZh,jdbcType=VARCHAR},

#{parentId,jdbcType=INTEGER},

#{showOrder,jdbcType=INTEGER},

#{deleteStatus,jdbcType=BIT},

#{description,jdbcType=VARCHAR}

)

</insert>

UUID:

在Oracle中:

<insert id="insert" parameterType="com.xxx.SystemDepartment">

    <selectKey keyProperty="id" resultType="String" order="BEFORE">

        select sys_guid() from dual

    </selectKey>

    insert into SYSTEM_DEPARTMENT (ID,DEPNAME, SUPERID, SORT, STATE)

    values ( #{id,jdbcType=VARCHAR},#{depname,jdbcType=VARCHAR},

    #{superid,jdbcType=DECIMAL}, #{sort,jdbcType=DECIMAL},

    #{state,jdbcType=DECIMAL})

</insert>

在Mysql中:

<insert id="insert" parameterType="com.xxx.SystemDepartment">

    <selectKey keyProperty="id" resultType="String" order="BEFORE">

        SELECT UUID()

    </selectKey>

    insert into SYSTEM_DEPARTMENT (ID,DEPNAME, SUPERID, SORT, STATE)

    values ( #{id,jdbcType=VARCHAR},#{depname,jdbcType=VARCHAR},

    #{superid,jdbcType=INTEGER}, #{sort,jdbcType=INTEGER},

    #{state,jdbcType=INTEGER})

</insert>

注:UUID如不需要连字符'-'可以使用数据库函数进行处理,如mysql:  select  replace(uuid(),'-','')   UUID  ;

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!