The role of Mybatis useGeneratedKeys properties and keyProperty

Reference Links: https://blog.csdn.net/fengkungui/article/details/82772302

                    https://www.iteye.com/blog/bugyun-2286145

                   https://blog.csdn.net/weixin_40936211/article/details/90577603

When using mybatis, is there such a demand:

         In mybatis profile, and a man named keyProperty useGeneratedKeys properties. useGeneratedKeys parameters only for insert statements into effect, the default is false. When set to true, it indicates if the inserted auto-increment primary key in the table, JDBC support allows automatic generation of primary keys, and the primary key returned automatically generated.

     When the primary key is auto-incremented case, add a record at the same time, its primary key can not be used, but sometimes we need the primary key, then how do we deal with it? Then we only need to add the following attributes in the corresponding xml:

        useGeneratedKeys = "true" keyProperty = "corresponding to the primary key of an object." id growth in the value of the object to ensure Notice obtained after by mybatis added to the database will be set in the Notice object.

<!--   主要是在主键是自增的情况下,添加成功后可以直接使用主键值,其中keyProperty的值是对象的属性值不是数据库表中的字段名-->
    <insert id="saveMsg" parameterType="Notice" useGeneratedKeys="true" keyProperty="msgId">
        insert into notice(msg_type,title,content,rec_time,send_time,user_id,deleted,viewed)
        values(#{msgType,jdbcType=INTEGER},#{title,jdbcType=VARCHAR},#{content,jdbcType=VARCHAR},
               #{recTime,jdbcType=BIGINT},#{sendTime,jdbcType=BIGINT},#{userId,jdbcType=VARCHAR},
               #{deleted,jdbcType=TINYINT},#{viewed,jdbcType=INTEGER})
    </insert>

So that after the java code we can obtain an attribute value (msgId) corresponding to the key of the main object.

Published 100 original articles · won praise 47 · views 210 000 +

Guess you like

Origin blog.csdn.net/sl1990129/article/details/102919424