JavaMVC框架

MyBatis中在插入数据后,对象立刻获取Id的方法

2018-06-25  本文已影响0人  Belmode

只列举最主要的部分

方法一(获取自增主键,拥有自增主键的数据库例如:MySQL)


insert标签中,加入keyPropertyuseGeneratedKeys两个属性:

    <!-- MySQL中获取主键并插入1 -->
    <insert id="insertUser" parameterType="user" keyProperty="userId" useGeneratedKeys="true">
        insert into USER(u_id, u_name, u_pwd) values(#{userId}, #{userName}, #{userPassword})
    </insert>

useGeneratedKeys设置为true,keyProperty设置为出入对象的主键属性
这样,在执行了insertUser(User user) 方法后,是能取出user.userId的。

方法二(获取非自增主键的值,没有原始自增主键的数据库例如:Oracle)


在insert标签中,添加selectKey子标签:

    <!-- MySQL中获取主键并插入2 -->
    <insert id="insertUser2" parameterType="user">
        <selectKey keyProperty="userId" resultType="string" order="AFTER"
            statementType="PREPARED">
            SELECT @@IDENTITY as userId
        </selectKey>
        insert into USER(u_id, u_name, u_pwd) values(#{userId}, #{userName}, #{userPassword})
    </insert>

另外,在MySQL中还有种方法能够查到主键值:

<!-- MySQL中获取主键并插入3 -->
    <insert id="insertUser3" parameterType="user">
        <selectKey keyProperty="userId" resultType="string" order="AFTER"
            statementType="PREPARED">
            SELECT LAST_INSERT_ID() AS userId
        </selectKey>
        insert into USER(u_id, u_name, u_pwd) values(#{userId}, #{userName}, #{userPassword})
    </insert>

SELECT LAST_INSERT_ID() AS userId是MySQL提供的一个聚合函数,也能够查询到最新的主键值,同上面一样,也只能在插入操作后才能进行查询,否则值为 0。后面的别名也可以省略。

既然,MySQL可以这么操纵,那么要是没有主键的Oracle该怎么办呢?

注意:由于Oracle中没有主键,所以只能使用第二种方式。

所以其实,可以同过selectKey+序列的形式,来模拟主键
(弊端就是,此时的为主键是没有约束的,但是可以设置唯一,不过就增加了麻烦了)

 <!-- Oracle中获取主键并插入 1 -->
    <insert id="insertUser" parameterType="user" databaseId="oracle">
        <selectKey databaseId="oracle" order="BEFORE" resultType="string"
            keyProperty="userId">
            select user_id_seq.nextval from dual
        </selectKey>
        insert into OUSER(u_id, u_name, u_pwd, u_sex) values(#{userId}, #{userName}, #{userPassword}, '1')
    </insert>

    <!-- Oracle中获取主键并插入 2 -->
    <insert id="insertUser2" parameterType="user" databaseId="oracle">
        <selectKey databaseId="oracle" order="AFTER" resultType="string"
            keyProperty="userId">
            select user_id_seq.currval from dual
        </selectKey>
        insert into OUSER(u_id, u_name, u_pwd, u_sex) values(user_id_seq.nextval, #{userName},#{userPassword},
        '1')
    </insert>

通过上面的xml配置可以看出来,其实和MySQL没有多大区别。

这个稍微注意一下就OK了。

上一篇 下一篇

猜你喜欢

热点阅读