MyCat批量插入

1. 概述

web項(xiàng)目使用 mybatis+mycat+mysql 的結(jié)構(gòu)。
mycat作為中間件,mysql 使用多庫分表

存在兩張表:t_table(表的元數(shù)據(jù)信息) 和 t_table_field(表的字段信息)。
邏輯上,t_table_field 是作為 t_table 的子表。

t_table_field 某業(yè)務(wù)需求,為了減少 mybatis <> mycat 之間的網(wǎng)絡(luò)IO,考慮使用批量插入數(shù)據(jù)。

mycat要使用批量插入數(shù)據(jù),需要注意一下兩點(diǎn):

  1. schema.xml<schema> 配置中,只有 <table> 支持(<childTable> 不支持)。
  2. 表的主鍵ID使用mycat的自增ID策略,需要配置 primaryKey autoIncrement 屬性。

2. 示例

2.1. Pojo

@Setter
@Getter
public class TableField {
    private Long id;
    private Long pid; // t_table主鍵
    private String fieldName;
    private String fieldType;
    private String isNull;
    private String defaultValue;
    private String expand;
    private String comment;
    private Integer position;
    private Date createTime;
}

2.2. Mapper

/**
 * 批量插入
 */
void insertByBatch(@Param("pid") Long pid, @Param("fieldList") List<TableField> fieldList);

sql需要指明 Catlet -> BatchInsertSequence

<insert id="insertByBatch" parameterType="map">
    /*!mycat:catlet=io.mycat.route.sequence.BatchInsertSequence */
    insert into t_table_field(pid,field_name,field_type,is_null,default_value,expand,comment,`position`,create_time)
    values
    <foreach collection="fieldList" item="item" index="index" separator=",">
        (#{pid},#{item.fieldName},#{item.fieldType},#{item.isNull},#{item.defaultValue},#{item.expand},
        #{item.comment},#{item.position},#{item.createTime})
    </foreach>
</insert>

2.3. MyCat配置

sequence_db_conf.properties

這里使用 properties+表 配置sequence

T_TABLE=dn1
T_TABLE_FIELD=dn1

schema.xml

<schema ···>
  <table name="mycat_sequence" dataNode="dn1"/>

  <table name="t_table" dataNode="dn$8-9" rule="sharding-by-id-2"/>
  <table name="t_table_field" primaryKey="id" autoIncrement="true" dataNode="dn$8-9" rule="sharding-by-id-2"/>
</schema>

t_tablet_table_field 表分了2個(gè)節(jié)點(diǎn),rule 是根據(jù)ID取模(id % 2)分片。
t_table_field 表的配置要聲明 primaryKey autoIncrement 屬性。

2.4. 實(shí)際執(zhí)行SQL

MyCat實(shí)際發(fā)送到MySQL的SQL是組裝上 ID 字段的

2020/06/21 16:09:56.747 | jvm 1    | {INSERT INTO T_TABLE_FIELD (pid, field_name, field_type, is_null, default_value, expand, comment, `position`, create_time, ID)
2020/06/21 16:09:56.747 | jvm 1    | VALUES (20157, 'id', 'varchar(20)', '0', NULL, '', '主鍵id', 0, '2020-06-21 16:09:56.845'
2020/06/21 16:09:56.747 | jvm 1    |            , 14086050),
2020/06/21 16:09:56.747 | jvm 1    |    (20157, 'sub_inventory_code', 'varchar(32)', '0', NULL, '', '子盤點(diǎn)單號', 2, '2020-06-21 16:09:56.845'
2020/06/21 16:09:56.747 | jvm 1    |            , 14086112)}, respHandler=io.mycat.backend.mysql.nio.handler.MultiNodeQueryHandler@3f60f0a6, ······
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容