项目踩坑之MyBatis 转换大小写问题

项目踩坑之MyBatis 转换大小写问题

由于在Windows环境下MySQL数据库不严格区分大小写,所以我们在对数据库的表和字段进行命名时两个单词之间都是使用下划线“_”的,比如“user_name”。但是,我们在项目开发时,为了遵守代码规范,实体类中的属性采用的都是驼峰式命名。这样,MyBatis可能就会报错没有该属性的get和set方法。

解决方法:
1.使用resultMap,通过resultMap中的column值(数据库字段名)和property值(实体类属性名)进行一一映射。

<?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.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.domain.User">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="user_name" jdbcType="VARCHAR" property="userName" />
    <result column="password" jdbcType="VARCHAR" property="password" />
    
  </resultMap>
  <select id="xxx" parameterType="xxx" resultMap="BaseResultMap" >
  ......
  </select>

2.对MyBatis进行配置:
(1)在mybatis-config.xml配置文件中添加以下代码:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 
<configuration>
	<!-- 配置mybatis自动转换为驼峰命名 -->
	<settings>
		<setting name="mapUnderscoreToCamelCase" value="true" />
	</settings>
</configuration>

(2) 在application.yml文件中进行配置:

#mybatis配置
mybatis:
	configuration:
	  map-underscore-to-camel-case: true

其中的map-underscore-to-camel-case也可以写成mapUnderscoreToCamelCase(未尝试),然后MyBatis的xml文件中直接使用对应的实体类来接收数据。

<?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.mapper.UserMapper">
  <select id="xxx" parameterType="xxx" resultType="User" >
  ......
  </select>

第(1)种方式和第(2)种方式同时配置时,第(2)种方式的优先级更高。(参考其他博客)
3.自定义配置类的方式配置:给容器中添加一个ConfigurationCustomizer。

@Configuration
public class MyBatisConfig {
    
    
    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
    
    
        return new ConfigurationCustomizer() {
    
    
            @Override
            public void customize(org.apache.ibatis.session.Configuration configuration) {
    
    
                configuration.setMapUnderscoreToCamelCase(true);
            }
        };
    }
}

前两种方式参考博客:https://blog.csdn.net/qq_38738510/article
第三种方式参考博客:https://blog.csdn.net/liu_sisi/article/details/88360155

猜你喜欢

转载自blog.csdn.net/problemRecord/article/details/115251589