1. 通过XML映射文件中的resultMap
<mapper namespace="data.UserMapper">
<resultMap type="data.User" id="userResultMap">
<!-- 用id属性来映射主键字段 -->
<id property="id" column="user_id"/>
<!-- 用result属性来映射非主键字段 -->
<result property="userName" column="user_name"/>
</resultMap>
</mapper>
2. 通过属性配置完成映射
使用者最陌生的是通过配置属性来完成映射,Mybatis给我们提供了一种映射方式,如果属性的命名是遵从驼峰命名法的,数据列名遵从下划线命名,
那么可以使用这种方式,类似如下:
- userName对应user_name;
- userId对应user_id;
配置代码如下:
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
Configuration configuration = new Configuration();
configuration.setMapUnderscoreToCamelCase(true);
sqlSessionFactoryBean.setConfiguration(configuration);
SpringMVC中配置方式:
在配置文件中添加配置如下
<configuration> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> </configuration>
SpringBoot配置方式:
application.yml中添加配置如下
mybatis:
configuration:
map-underscore-to-camel-case: true
mapperLocations: mybatis/**/*Mapper.xml
typeAliasesPackage: com.lny