Caused by: org.apache.ibatis.reflection.ReflectionException: Could not set property ‘id‘ of ‘class

小灰灰 2023-02-27 13:31 136阅读 0赞

问题描述

Caused by: org.apache.ibatis.reflection.ReflectionException: Could not set property ‘id’ of ‘class XXX’ with value ‘XXX’ Cause: java.lang.IllegalArgumentException: argument type mismatch

这是mybatis保存数据时报的一个错,跟着源码找了一下原因。如下:

因为mybatis的全局配置com.baomidou.mybatisplus.core.config.GlobalConfig.DbConfig中,主键类型默认是ID_WORKER。

  1. public static class DbConfig {
  2. /** * 主键类型(默认 ID_WORKER) */
  3. private IdType idType = IdType.ID_WORKER;

在表对应的实体类加载时,主键初始化流程中com.baomidou.mybatisplus.core.metadata.TableInfoHelper#initTableIdWithoutAnnotation,如果数据库表对应的实体类中有个字段名为id,会被默认当做存在的主键,并且设置主键自动生成器为全局配置的IdType.

  1. /** * 默认表主键名称 */
  2. private static final String DEFAULT_ID_NAME = "id";
  3. /** * <p> * 主键属性初始化 * </p> * * @param tableInfo 表信息 * @param field 字段 * @param clazz 实体类 * @return true 继续下一个属性判断,返回 continue; */
  4. private static boolean initTableIdWithoutAnnotation(GlobalConfig.DbConfig dbConfig, TableInfo tableInfo,
  5. Field field, Class<?> clazz) {
  6. // 省略......
  7. if (DEFAULT_ID_NAME.equalsIgnoreCase(column)) {
  8. if (StringUtils.isEmpty(tableInfo.getKeyColumn())) {
  9. tableInfo.setKeyRelated(checkRelated(tableInfo.isUnderCamel(), field.getName(), column))
  10. .setIdType(dbConfig.getIdType())
  11. .setKeyColumn(column)
  12. .setKeyProperty(field.getName())
  13. .setKeyType(field.getType());
  14. return true;
  15. } else {
  16. throwExceptionId(clazz);
  17. }
  18. }
  19. return false;
  20. }

在调用insert类型的方法时,如果主键为空,会根据IdType的类型来填充主键,生成主键的方法是IdWorker.getId()

  1. /** * 自定义元对象填充控制器 * * @param metaObjectHandler 元数据填充处理器 * @param tableInfo 数据库表反射信息 * @param ms MappedStatement * @param parameterObject 插入数据库对象 * @return Object */
  2. protected static Object populateKeys(MetaObjectHandler metaObjectHandler, TableInfo tableInfo,
  3. MappedStatement ms, Object parameterObject, boolean isInsert) {
  4. // 省略......
  5. // 填充主键
  6. if (isInsert && !StringUtils.isEmpty(tableInfo.getKeyProperty())
  7. && null != tableInfo.getIdType() && tableInfo.getIdType().getKey() >= 3) {
  8. Object idValue = metaObject.getValue(tableInfo.getKeyProperty());
  9. /* 自定义 ID */
  10. if (StringUtils.checkValNull(idValue)) {
  11. if (tableInfo.getIdType() == IdType.ID_WORKER) {
  12. metaObject.setValue(tableInfo.getKeyProperty(), IdWorker.getId());
  13. } else if (tableInfo.getIdType() == IdType.ID_WORKER_STR) {
  14. metaObject.setValue(tableInfo.getKeyProperty(), IdWorker.getIdStr());
  15. } else if (tableInfo.getIdType() == IdType.UUID) {
  16. metaObject.setValue(tableInfo.getKeyProperty(), IdWorker.get32UUID());
  17. }
  18. }
  19. }
  20. // 省略......
  21. }

IdWorker.getId()方法是通过时间戳生成的一个lang类型的随机数,此时如果我们的id类型是Integer,就会报错argument type mismatch了。

发表评论

表情:
评论列表 (有 0 条评论,136人围观)

还没有评论,来说两句吧...

相关阅读