Policy failure official documentation in using Sharding JDBC to generate distributed ids
spring.shardingsphere.sharding.tables.t_order_item.key-generator.column=order_item_id
spring.shardingsphere.sharding.tables.t_order_item.key-generator.type=SNOWFLAKE
Copy the code
Local YAML configuration
spring:
application:
name: note
shardingsphere:
enabled: true
sharding:
tables:
t_order:
keyGenerator:
column: id
# UUID SNOWFLAKE
type: SNOWFLAKE
# Optional configuration
props:
worker-id: 132
Copy the code
According to the official configuration, it should be correct to configure a generate column and generate algorithm but it still fails to be inserted into the table because this key is a primary key and cannot be empty. Using this distributed ID generation algorithm, the ID fails to be empty
Configuration is ok so let’s take a look at the Mapper insert layer because using Mybatsi take a look at mapper
/** * Add all fields of the object **@paramOrder inserts field object (must contain ID) *@return int
*/
@Insert("insert into t_order(id,user_id,order_sn,gmt_create,gmt_update) values(null,#{userId},#{orderSn},#{gmtCreate},#{gmtUpdate})")
int insert(Order order);
Copy the code
This is not a problem because we used mysql to increment the ID and now we have a problem with the distributed ID
/** * Add all fields of the object **@paramOrder inserts field object (must contain ID) *@return int
*/
@Insert("insert into t_order(user_id,order_sn,gmt_create,gmt_update) values(#{userId},#{orderSn},#{gmtCreate},#{gmtUpdate})")
int insert(Order order);
Copy the code
Direct SQL layer does not operate ID let Sharding JDBC help us to generate distributed ID after modification, the distributed ID will be generated successfullySharding JDBC Failed to generate distributed IDS
- Mapper layer error shown above
- Distributed ids that generate keys or increment cannot increment
- If the type of ID is not correct, the ID will not be stored. For example, if the snowflake algorithm generates an ID of 18 bits long, you will not be able to store it if you use an int
- Custom build algorithm error or SPI mechanism cannot find
End hopes to help you