Mybatis-类属性和数据库字段映射方式

1. 通过XML映射文件中的resultMap
<mapper namespace="data.UserMapper">
    <resultMap type="data.User" id="userResultMap">
        
        <id property="id" column="user_id"/>
        
        <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中配置方式:

在配置文件中添加配置如下


    
        
    


SpringBoot配置方式:

application.yml中添加配置如下

mybatis:
  configuration:
    map-underscore-to-camel-case: true
  mapperLocations: mybatis/**/*Mapper.xml
  typeAliasesPackage: com.lny




你可能感兴趣的:(Mybatis-类属性和数据库字段映射方式)