最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Mybatis3中方法返回生成的主鍵:XML,@SelectKey,@Options詳解

 更新時間:2024年01月27日 09:10:18   作者:小子寶丁  
這篇文章主要介紹了Mybatis3中方法返回生成的主鍵:XML,@SelectKey,@Options,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教

需求

在很多業(yè)務(wù)場景中,我們希望插入一條記錄時就返回該記錄的相關(guān)信息,返回主鍵顯得尤為重要。

解決方案

1、XML中配置

在定義xml映射器時設(shè)置屬性useGeneratedKeys值為true,并分別指定屬性keyProperty和keyColumn為對應(yīng)的數(shù)據(jù)庫記錄主鍵字段與Java對象的主鍵屬性。

key釋意
useGeneratedKeys取值范圍true/false(默認值),設(shè)置是否使用JDBC的getGenereatedKeys方法獲取主鍵并賦值到keyProperty設(shè)置的領(lǐng)域模型屬性中。MySQL和SQLServer執(zhí)行auto-generated key field,因此當(dāng)數(shù)據(jù)庫設(shè)置好自增長主鍵后,可通過JDBC的getGeneratedKeys方法獲取。但像Oralce等不支持auto-generated key field的數(shù)據(jù)庫就不能用這種方法獲取主鍵了
keyProperty默認值unset,用于設(shè)置getGeneratedKeys方法或selectKey子元素返回值將賦值到領(lǐng)域模型的哪個屬性中
keyColumn設(shè)置數(shù)據(jù)表自動生成的主鍵名。對特定數(shù)據(jù)庫(如PostgreSQL),若自動生成的主鍵不是第一個字段則必須設(shè)置

自增主鍵

<insert id="insert" parameterType="com.xzbd.User" useGeneratedKeys=”true” keyProperty=”id”>
  insert into user (username,password,email,bio) values (#{username},#{password},#{email},#{bio})
</insert>

使用標(biāo)簽selectKeyselect LAST_INSERT_ID()

   <!-- mysql的自增ID :LAST_INSERT_ID -->
    <insert id="inserUser2" parameterType="com.xzbd.User" >
        <selectKey keyProperty="user_id" order="AFTER" resultType="java.lang.Integer">
            select LAST_INSERT_ID()
        </selectKey> 
        insert into t_user(name,age) value(#{name},#{age})
    </insert>

非自增,UUID

    <insert id="inserUser4" parameterType="com.xzbd.User" >
        <selectKey keyProperty="user_id" order="AFTER" resultType="java.lang.Integer">
            select uuid()
        </selectKey>
        insert into t_user(user_id,name,age) value(#{user_id},#{name},#{age})
    </insert>

2、Mapper中使用@SelectKey或@Options注解配置

@SelectKey注解的功能與 <selectKey>標(biāo)簽完全一致,用在已經(jīng)被@Insert@InsertProvider@Update 、@UpdateProvider 注解了的方法上。

在未被上述四個注解的方法上作 @SelectKey 注解則視為無效。

如果你指定了 @SelectKey注解,那么 MyBatis 就會忽略掉由 @Options 注解所設(shè)置的生成主鍵或設(shè)置(configuration)屬性,即@SelectKey@Options不應(yīng)同時使用。

  • @SelectKey
屬性描述
keyPropertyselectKey 語句結(jié)果應(yīng)該被設(shè)置的目標(biāo)屬性。
resultType結(jié)果的類型。MyBatis 通??梢运愠鰜?但是寫上也沒有問題。MyBatis 允許任何簡單類型用作主鍵的類型,包括字符串。
order這可以被設(shè)置為 BEFORE 或 AFTER。如果設(shè)置為 BEFORE,那么它會首先選擇主鍵,設(shè)置 keyProperty 然后執(zhí)行插入語句。如果設(shè)置為 AFTER,那么先執(zhí)行插入語句,然后是 selectKey 元素-這和如 Oracle 數(shù)據(jù)庫相似,可以在插入語句中嵌入序列調(diào)用。
statementType和前面的相 同,MyBatis 支持 STATEMENT ,PREPARED 和CALLABLE 語句的映射類型,分別代表 PreparedStatement 和CallableStatement 類型。

示例如下:

@Insert("insert into user (name) values(#{name})")  
@SelectKey(statement="select LAST_INSERT_ID()", keyProperty="id", before=false, resultType=int.class)  
int insert(String name);

  • @Options

該注解能更精細化的控制SQL執(zhí)行,其代碼如下:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Options {
    boolean useCache() default true;
    boolean flushCache() default false;
    ResultSetType resultSetType() default ResultSetType.FORWARD_ONLY;
    StatementType statementType() default StatementType.PREPARED;
    int fetchSize() default -1;
    int timeout() default -1;
    boolean useGeneratedKeys() default false;
    String keyProperty() default "id";
    String keyColumn() default "";
}

示例如下:

    @InsertProvider(type = SqlProviderAdapter.class, method = "insert")
    @SelectKey(
            keyProperty = "record.id", before = false,
            resultType = Long.class,statement = {"select last_insert_id()"}
    )
    int insert(InsertStatementProvider<User> insertStatement);

3、特別案例MyBatis Dynamic SQL

官方文檔中Insert Statements描述如下

MyBatis supports returning generated values from a single row insert, or a batch insert. In either case, it is simply a matter of configuring the insert mapper method appropriately. For example, to retrieve the value of a calculated column configure your mapper method like this:

...
    @InsertProvider(type=SqlProviderAdapter.class, method="insert")
    @Options(useGeneratedKeys=true, keyProperty="row.fullName")
    int insert(InsertStatementProvider<GeneratedAlwaysRecord> insertStatement);
...

The important thing is that the keyProperty is set correctly. It should always be in the form row. where is the attribute of the record class that should be updated with the generated value.

注意

keyProperty="row.fullName” 中的row不一定正確,按照這個寫后,會報錯

org.apache.ibatis.executor.ExecutorException: No setter found for the keyProperty 'xxx' in …… DefaultInsertStatementProvider

的異常,改為 keyProperty="fullName“ 也會報異常,通過查看 DefaultInsertStatementProvider 源碼

最終通過代碼為

keyProperty="rocord.fullName” 

4、批量插入

批量插入和單條插入差不多, MyBatis Dynamic SQL批量插入案例如下。

MyBatis supports returning generated values from a multiple row insert statement with some limitations.

The main limitation is that MyBatis does not support nested lists in parameter objects.

Unfortunately, the MultiRowInsertStatementProvider relies on a nested List.

It is likely this limitation in MyBatis will be removed at some point in the future, so stay tuned.

Nevertheless, you can configure a mapper that will work with the MultiRowInsertStatementProvider as created by this library.

The main idea is to decompose the statement from the parameter map and send them as separate parameters to the MyBatis mapper. For example:

...
    @InsertProvider(type=SqlProviderAdapter.class, method="insertMultipleWithGeneratedKeys")
    @Options(useGeneratedKeys=true, keyProperty="records.fullName")
    int insertMultipleWithGeneratedKeys(String insertStatement, @Param("records") List<GeneratedAlwaysRecord> records);

    default int insertMultipleWithGeneratedKeys(MultiRowInsertStatementProvider<GeneratedAlwaysRecord> multiInsert) {
        return insertMultipleWithGeneratedKeys(multiInsert.getInsertStatement(), multiInsert.getRecords());
    }
...

The first method above shows the actual MyBatis mapper method.

Note the use of the @Options annotation to specify that we expect generated values.

Further, note that the keyProperty is set to records.fullName - in this case, fullName is a property of the objects in the records List.

The library supplied adapter method will simply return the insertStatement as supplied in the method call.

The adapter method requires that there be one, and only one, String parameter in the method call, and it assumes that this one String parameter is the SQL insert statement.

The parameter can have any name and can be specified in any position in the method’s parameter list.

The @Param annotation is not required for the insert statement. However, it may be specified if you so desire.

The second method above decomposes the MultiRowInsertStatementProvider and calls the first method.

結(jié)論

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Spring Boot集成Druid出現(xiàn)異常報錯的原因及解決

    Spring Boot集成Druid出現(xiàn)異常報錯的原因及解決

    Druid 可以很好的監(jiān)控 DB 池連接和 SQL 的執(zhí)行情況,天生就是針對監(jiān)控而生的 DB 連接池。本文講述了Spring Boot集成Druid項目中discard long time none received connection異常的解決方法,出現(xiàn)此問題的同學(xué)可以參考下
    2021-05-05
  • SpringBoot實現(xiàn)微信及QQ綁定登錄的示例代碼

    SpringBoot實現(xiàn)微信及QQ綁定登錄的示例代碼

    本文主要介紹了SpringBoot實現(xiàn)微信及QQ綁定登錄的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-07-07
  • java文件刪除不了的坑,特別是壓縮文件問題

    java文件刪除不了的坑,特別是壓縮文件問題

    這篇文章主要介紹了java文件刪除不了的坑,特別是壓縮文件問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-06-06
  • 關(guān)于接口ApplicationContext中的getBean()方法使用

    關(guān)于接口ApplicationContext中的getBean()方法使用

    這篇文章主要介紹了關(guān)于接口ApplicationContext中的getBean()方法使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-09-09
  • Java實現(xiàn)簡單學(xué)生信息管理系統(tǒng)

    Java實現(xiàn)簡單學(xué)生信息管理系統(tǒng)

    這篇文章主要為大家詳細介紹了Java實現(xiàn)簡單學(xué)生信息管理系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • Spring 4 支持的 Java 8 特性

    Spring 4 支持的 Java 8 特性

    Spring 框架 4 支持 Java 8 語言和 API 功能。在本文中,我們將重點放在 Spring 4 支持新的 Java 8 的功能。最重要的是 Lambda 表達式,方法引用,JSR-310的日期和時間,和可重復(fù)注釋。下面跟著小編一起來看下吧
    2017-03-03
  • 阿里云OSS域名配置及簡單上傳的示例代碼

    阿里云OSS域名配置及簡單上傳的示例代碼

    這篇文章主要介紹了阿里云OSS域名配置及簡單上傳的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • 基于jfreechart生成曲線、柱狀等圖片并展示到JSP

    基于jfreechart生成曲線、柱狀等圖片并展示到JSP

    這篇文章主要介紹了基于jfreechart生成曲線、柱狀等圖片并展示到JSP,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-10-10
  • IDEA修改idea64.exe.vmoptions文件以及解決coding卡頓問題

    IDEA修改idea64.exe.vmoptions文件以及解決coding卡頓問題

    IDEA修改idea64.exe.vmoptions文件以及解決coding卡頓問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2023-04-04
  • SpringBoot之Refresh流程的簡單說明

    SpringBoot之Refresh流程的簡單說明

    這篇文章主要介紹了SpringBoot之Refresh流程的簡單說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09

最新評論

贵溪市| 睢宁县| 永仁县| 高唐县| 海伦市| 富阳市| 铜梁县| 平乐县| 天等县| 台江县| 武城县| 永嘉县| 镇宁| 张掖市| 洛川县| 武定县| 枣阳市| 禄劝| 濉溪县| 白山市| 会泽县| 瑞安市| 海宁市| 三穗县| 云阳县| 夏邑县| 剑川县| 揭西县| 青海省| 龙江县| 界首市| 沙洋县| 新乐市| 融水| 右玉县| 壶关县| 沅陵县| 万荣县| 同江市| 桓仁| SHOW|