1. 概述
web项目使用 mybatis+mycat+mysql 的结构。
mycat作为中间件,mysql 使用多库分表
存在两张表:t_table
(表的元数据信息) 和 t_table_field
(表的字段信息)。
逻辑上,t_table_field
是作为 t_table
的子表。
t_table_field
某业务需求,为了减少 mybatis <> mycat 之间的网络IO,考虑使用批量插入数据。
mycat要使用批量插入数据,需要注意一下两点:
- 在
schema.xml
的<schema>
配置中,只有<table>
支持(<childTable>
不支持)。 - 表的主键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_table
和 t_table_field
表分了2个节点,rule 是根据ID取模(id % 2)分片。
t_table_field
表的配置要声明 primaryKey
autoIncrement
属性。
2.4. 实际执行SQL
MyCat实际发送到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, '', '子盘点单号', 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, ······
网友评论