1. 首页
  2. >
  3. 编程技术
  4. >
  5. Java

mybatis plus字段名称有下划线读取不到值的问题

问题

环境:springboot + mybatis-plus

现在有这么一个实体

package com.ct10000.sc.pc.videoauth.entity;   import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableName;  import java.io.Serializable;  @TableName(value = "your_table") public class Info implements Serializable {      /**      * 姓名      */     @TableField(value = "PERSON_NAME")     private String person_name;       public String getPerson_name() {         return person_name;     }      public void setPerson_name(String person_name) {         this.person_name = person_name;     } } 

实体有一个字段叫person_name,并且我指定了数据库里面的字段为PERSON_NAME(TableField注解),但是查询的时候值为null,其他不带下划线的字段值正常

用大腿都能想到肯定和下划线有关系,最终在mybatis-plus官网找到这么一段话:

# 官网 https://mp.baomidou.com/guide/faq.html#cause-org-apache-ibatis-type-typeexception-error-setting-null-for-parameter-1-with-jdbctype-other  MybatisConfiguration configuration = new MybatisConfiguration(); configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class); configuration.setJdbcTypeForNull(JdbcType.NULL); configuration.setMapUnderscoreToCamelCase(true);//开启下划线转驼峰 sqlSessionFactory.setConfiguration(configuration);

开启了下划线转驼峰,这不多此一举吗,我都指定了实体字段和数据库字段的映射关系,偏还给我转驼峰,转成personName了,一看实体里面没有personName当然是null了

解决

所以你只要告诉mybatis-plus我不要下划线转驼峰即可,mybatis-plus底层也就是mybatis,总之不管什么方式,你要配置一下,如下是yml配置

 mybatis-plus:   configuration:     map-underscore-to-camel-case: false # 数据库下划线自动转驼峰标示关闭     

或者properties格式配置mybatis

mybatis.configuration.map-underscore-to-camel-case=true

源码

在org.apache.ibatis.reflection.MetaClass的方法findProperty里面:

public String findProperty(String name, boolean useCamelCaseMapping) {     if (useCamelCaseMapping) {       name = name.replace("_", "");     }     return findProperty(name); }

如果设置了useCamelCaseMapping为true,就简单粗暴的把下划线干掉了