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

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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值