question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

UUID is configured, but SNOWFLAKE is used

See original GitHub issue

Question

UUID is configured, but SNOWFLAKE is used

errorMsg

Caused by: org.apache.ibatis.reflection.ReflectionException: Could not set property 'code' of 'class com.project.modular.code.entity.UserCode' with value '1249941032855007234' Cause: java.lang.IllegalArgumentException: argument type mismatch
	at org.apache.ibatis.reflection.wrapper.BeanWrapper.setBeanProperty(BeanWrapper.java:185)
	at org.apache.ibatis.reflection.wrapper.BeanWrapper.set(BeanWrapper.java:59)
	at org.apache.ibatis.reflection.MetaObject.setValue(MetaObject.java:140)
	at com.baomidou.mybatisplus.core.MybatisDefaultParameterHandler.populateKeys(MybatisDefaultParameterHandler.java:178)
	at com.baomidou.mybatisplus.core.MybatisDefaultParameterHandler.processBatch(MybatisDefaultParameterHandler.java:120)
	at com.baomidou.mybatisplus.core.MybatisDefaultParameterHandler.<init>(MybatisDefaultParameterHandler.java:51)
	at com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver.createParameterHandler(MybatisXMLLanguageDriver.java:34)
	at com.baomidou.mybatisplus.core.MybatisXMLLanguageDriver.createParameterHandler(MybatisXMLLanguageDriver.java:28)
	at org.apache.ibatis.session.Configuration.newParameterHandler(Configuration.java:550)
	at org.apache.ibatis.executor.statement.BaseStatementHandler.<init>(BaseStatementHandler.java:69)
	at org.apache.ibatis.executor.statement.PreparedStatementHandler.<init>(PreparedStatementHandler.java:41)
	at org.apache.ibatis.executor.statement.RoutingStatementHandler.<init>(RoutingStatementHandler.java:46)
	at org.apache.ibatis.session.Configuration.newStatementHandler(Configuration.java:563)
	at org.apache.ibatis.executor.SimpleExecutor.doUpdate(SimpleExecutor.java:48)
	at org.apache.ibatis.executor.BaseExecutor.update(BaseExecutor.java:117)
	at org.apache.ibatis.executor.CachingExecutor.update(CachingExecutor.java:76)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:198)
	at org.apache.ibatis.session.defaults.DefaultSqlSession.insert(DefaultSqlSession.java:185)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:433)
	... 68 common frames omitted

Version

springboot 2.0.6.RELEASE
mybatis-plus-boot-starter 3.1.0
sharding-jdbc-spring-boot-starter 4.0.0-RC1

TABLE

db0
  --user_code0
  --user_code1
db1
  --user_code0
  --user_code1
db2
  --user_code0
  --user_code1

yml

spring:
  shardingsphere:
    props:     
      sql:      #sql打印
        show: true   
    datasource:            #数据源配置
      names: db0,db1,db2   #数据库别名
      db0:                 #数据源具体配置
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/db0?characterEncoding=utf-8
        username: root
        password: root
      db1:                 #数据源具体配置
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/db1?characterEncoding=utf-8
        username: root
        password: root
      db2:                 #数据源具体配置
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://localhost:3306/db2?characterEncoding=utf-8
        username: root
        password: root
  sharding:       ##配置分库分表规则
      tables:       #具体策略                
        tab_user: 
          actual-data-nodes: db$->{0..2}.tab_user$->{0..1}  #具体的数据节点
          database-strategy:   #分库规则 
            inline:
              sharding-column: age
              algorithm-expression: db$->{age%3}
          table-strategy:
            inline:
              sharding-column: id     #按照id取模结果确定
              algorithm-expression: tab_user$->{id % 2}
          key-generator:    #配置主键生成策略
            column: id
            type: SNOWFLAKE
            props:
              worker:
                id: 20200413
        user_code:
          actual-data-nodes: db$->{0..2}.user_code$->{0..1}  #具体的数据节点   
          database-strategy:   #分库规则 
            inline:
              sharding-column: code
              algorithm-expression: db$->{Math.abs(code.hashCode() % 3)}         
          table-strategy:
            inline:
              sharding-column: code
              algorithm-expression: user_code$->{Math.abs(code.hashCode() % 2)}        
          key-generator:
            column: code
            type: UUID

sql

CREATE TABLE `db0`.`Untitled`  (
  `code` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '编号',
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '名字',
  `create_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间',
  `update_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '更新时间',
  PRIMARY KEY (`code`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '编码和名字对应表(测试UUID主键)' ROW_FORMAT = Dynamic;
CREATE TABLE `db0`.`Untitled`  (
  `code` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '编号',
  `name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '名字',
  `create_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '创建时间',
  `update_time` datetime(0) NULL DEFAULT CURRENT_TIMESTAMP(0) COMMENT '更新时间',
  PRIMARY KEY (`code`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '编码和名字对应表(测试UUID主键)' ROW_FORMAT = Dynamic;

CODE

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class UserCode extends Model<UserCode> {

    private static final long serialVersionUID = 1L;

    /**
     * 编号
     */
    @TableId(value = "code", type = IdType.NONE)
    private String code;

    /**
     * 名字
     */
    private String name;

    /**
     * 创建时间
     */
    private LocalDateTime createTime;

    /**
     * 更新时间
     */
    private LocalDateTime updateTime;


    @Override
    protected Serializable pkVal() {
        return this.code;
    }

}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.project.modular.code.mapper.UserCodeMapper">

    <!-- 通用查询结果列 -->
	<sql id="Base_Column_List">
     code AS code,  
     name AS name,  
     create_time AS createTime,  
     update_time AS updateTime  
	</sql>
</mapper>

public interface UserCodeMapper extends BaseMapper<UserCode> {

}
public interface IUserCodeService extends IService<UserCode> {

}
@Service
public class UserCodeServiceImpl extends ServiceImpl<UserCodeMapper, UserCode> implements IUserCodeService {

}
@RestController
@RequestMapping("/userCode")
public class UserCodeController {

    @Autowired
    private IUserCodeService userCodeService;

    @PostMapping("/saveSingle")
    public ResponseData<?> saveSingle(UserCode userCode) {
        userCodeService.save(userCode);
        return ResponseData.out(CodeEnum.SUCCESS, userCode.getCode());
    }
}

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:15 (8 by maintainers)

github_iconTop GitHub Comments

1reaction
flypangzhicommented, Apr 17, 2020

Ok, let’s close this issue.

Supplementary information

after my test,use mybatis-plus to generate codes,if the id generate by snowflake, Should use

 /**
     * 主键
     */
    @TableId(value = "id", type = IdType.NONE)
    private Long id;

or

  /**
     * 主键
     */
    @TableId(value = "id", type = IdType.ID_WORKER)
    private Long id;

if the id generate by UUID , Should use

@TableId(value = "code", type = IdType.UUID)
    private String code;
 @TableId(value = "code", type = IdType.AUTO)
    private String code;
1reaction
kimmkingcommented, Apr 16, 2020

with IdType.AUTO will use sharding-jdbc UUID key generator:

curl -X POST http://localhost:1000/userCode/save -H "Content-Type:application/json" --data "{\"name\":\"KK001\"}"
curl -X POST http://localhost:1000/userCode/save -H "Content-Type:application/json" --data "{\"name\":\"KK002\"}"

result:

[2020-04-16 22:01:01.178] [http-nio-1000-exec-9] [INFO ] ShardingSphere-SQL - Rule Type: sharding
[2020-04-16 22:01:01.178] [http-nio-1000-exec-9] [INFO ] ShardingSphere-SQL - Logic SQL: INSERT INTO user_code  ( name )  VALUES  ( ? )
[2020-04-16 22:01:01.178] [http-nio-1000-exec-9] [INFO ] ShardingSphere-SQL - SQLStatement: InsertStatement(super=DMLStatement(super=AbstractSQLStatement(type=DML, tables=Tables(tables=[Table(name=user_code, alias=Optional.absent())]), routeConditions=Conditions(orCondition=OrCondition(andConditions=[AndCondition(conditions=[])])), encryptConditions=Conditions(orCondition=OrCondition(andConditions=[])), sqlTokens=[TableToken(tableName=user_code, quoteCharacter=NONE, schemaNameLength=0), SQLToken(startIndex=23)], parametersIndex=1, logicSQL=INSERT INTO user_code  ( name )  VALUES  ( ? )), deleteStatement=false, updateTableAlias={}, updateColumnValues={}, whereStartIndex=0, whereStopIndex=0, whereParameterStartIndex=0, whereParameterEndIndex=0), columnNames=[name], values=[InsertValue(columnValues=[org.apache.shardingsphere.core.parse.old.parser.expression.SQLPlaceholderExpression@b8d9801])])
[2020-04-16 22:01:01.178] [http-nio-1000-exec-9] [INFO ] ShardingSphere-SQL - Actual SQL: db1 ::: INSERT INTO user_code1   (name, code) VALUES (?, ?) ::: [KK001, 1ec7581317d54399982411a1caa01f9f]
[2020-04-16 22:01:49.501] [http-nio-1000-exec-5] [INFO ] ShardingSphere-SQL - Rule Type: sharding
[2020-04-16 22:01:49.501] [http-nio-1000-exec-5] [INFO ] ShardingSphere-SQL - Logic SQL: INSERT INTO user_code  ( name )  VALUES  ( ? )
[2020-04-16 22:01:49.501] [http-nio-1000-exec-5] [INFO ] ShardingSphere-SQL - SQLStatement: InsertStatement(super=DMLStatement(super=AbstractSQLStatement(type=DML, tables=Tables(tables=[Table(name=user_code, alias=Optional.absent())]), routeConditions=Conditions(orCondition=OrCondition(andConditions=[AndCondition(conditions=[])])), encryptConditions=Conditions(orCondition=OrCondition(andConditions=[])), sqlTokens=[TableToken(tableName=user_code, quoteCharacter=NONE, schemaNameLength=0), SQLToken(startIndex=23)], parametersIndex=1, logicSQL=INSERT INTO user_code  ( name )  VALUES  ( ? )), deleteStatement=false, updateTableAlias={}, updateColumnValues={}, whereStartIndex=0, whereStopIndex=0, whereParameterStartIndex=0, whereParameterEndIndex=0), columnNames=[name], values=[InsertValue(columnValues=[org.apache.shardingsphere.core.parse.old.parser.expression.SQLPlaceholderExpression@b8d9801])])
[2020-04-16 22:01:49.501] [http-nio-1000-exec-5] [INFO ] ShardingSphere-SQL - Actual SQL: db1 ::: INSERT INTO user_code1   (name, code) VALUES (?, ?) ::: [KK002, b6da679a5e984acd8c9c44b4d192b100]

Read more comments on GitHub >

github_iconTop Results From Across the Web

UUID is configured, but SNOWFLAKE is used #5173 - GitHub
Caused by: org.apache.ibatis.reflection.ReflectionException: Could not set property 'code' of 'class com.project.modular.code.entity.
Read more >
Using the Search Optimization Service
This sets up search access paths to improve the performance of equality and IN predicate queries for all columns that use the supported...
Read more >
What Are Snowflake IDs?. How to generate unique IDs in a…
Universal Unique Identifiers is a well-known concept that's been used in software for years. A UUID is a 128-bit number that, when generated ......
Read more >
Get Full Details of UUID with Confection API on Query Results from ...
This integration creates a workflow with a Snowflake trigger and Confection action. When you configure and deploy the workflow, it will run on...
Read more >
The Wild World of Unique Identifiers (UUID, ULID, etc) - Medium
Type 5 — Like type 3 it is based on an input value but in this case it is SHA-1 hashed which is...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found