前言:
从SSM框架学到了springboot框架,我们都明白要想取到数据库中的值,必须保持数据库字段名与java类文件的属性名一致,那么mysql与java的命名原则不同,规范也不同,那我们应该如何解决这样的问题呢?
Mybatis中:
java中一般使用驼峰命名,而mysql使用下划线分割
数据库表列:user_name
实体类属性:userName
在mybatis中我们共有两种方式解决
方法一:起别名
在sql语句中为数据库的字段起一个别名再执行语句
<select id="getEmpByEmpId" resultType="com.songqiao.mybatis.pojo.User">
select user_name userName from t_user where user_id=#{user_id};
</select>
方法二:添加标签
在mybatis的主配置文件mybatis-config.xml中增加settings标签,采用mybatis的自带工具把下划线分割转换为驼峰命名
注意settings标签在配置文件中的位置,核心配置文件中的标签必须按照固定的顺序:
properties>settings>typeAliases>typeHandlers>objectFactory>objectWrapperFactory>reflectorFactory>plugins>environments>databaseIdProvider>mappers
<settings>
<!-- 映射下划线为驼峰 如果属性名与字段名没对上时使用 -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>
方法三:自定义映射ResultMap
若字段名和实体类中的属性名不一致,则可以通过resultMap设置自定义映射
<!--
若字段名和实体类中的属性名不一致,但是字段名符合数据库的规则(使用_),实体类中的属性
名符合Java的规则(使用驼峰)
此时也可通过以下两种方式处理字段名和实体类中的属性的映射关系
a>可以通过为字段起别名的方式,保证和实体类中的属性名保持一致
b>可以在MyBatis的核心配置文件中设置一个全局配置信息mapUnderscoreToCamelCase,可
以在查询表中数据时,自动将_类型的字段名转换为驼峰
例如:字段名user_name,设置了mapUnderscoreToCamelCase,此时字段名就会转换为userName
resultMap:设置自定义映射
属性:
id:表示自定义映射的唯一标识
type:查询的数据要映射的实体类的类型
子标签:
id:设置主键的映射关系
result:设置普通字段的映射关系
association:设置多对一的映射关系
collection:设置一对多的映射关系
属性:
property:设置映射关系中实体类中的属性名
column:设置映射关系中表中的字段名
-->
<resultMap id="userMap" type="User">
<id property="id" column="id"></id>
<result property="userName" column="user_name"></result>
<result property="password" column="password"></result>
<result property="age" column="age"></result>
<result property="sex" column="sex"></result>
</resultMap>
<!--List<User> testMohu(@Param("mohu") String mohu);-->
<select id="testMohu" resultMap="userMap">
<!--select * from t_user where username like '%${mohu}%'-->
select id,user_name,password,age,sex from t_user where user_name like
concat('%',#{mohu},'%')
</select>
springboot中:
方法一:更改配置文件
在application.yml配置文件里添加如下代码
mybatis:
configuration:
map-underscore-to-camel-case: true
或者在application.properties中添加如下代码
mybatis.configuration.map-underscore-to-camel-case:=true
方法二:写一个配置类
新建一个java文件,写入以下代码,建议放在config文件夹下,起名叫MyBatisConfig,开启驼峰对应规则
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author qiaoqiao
* @date 2023/4/15 15:11
*/
@Configuration
public class MyBatisConfig {
@Bean
public ConfigurationCustomizer configurationCustomizer(){
return new ConfigurationCustomizer() {
@Override
public void customize(org.apache.ibatis.session.Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}