Spring Boot 整合mybatis如何开启开启驼峰命名转换

如果在spring boot的配置文件中的数据源,在application.properties配置文件总加入以下配置即可:

1 mybatis.configuration.mapUnderscoreToCamelCase=true
2 或
3 mybatis.configuration.map-underscore-to-camel-case=true

如果是单独配置的数据源,则需要设定SqlSessionFactory中的

Configuration中的属性 mapUnderscoreToCamelCase 为 true

注意是这个类:org.apache.ibatis.session.Configuration

package com.moon.robot.dataSource;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.moon.robot.dao", sqlSessionTemplateRef = "robotSqlSessionTemplate")
public class RobotDataSourceConfig {

    @Bean(name = "robotDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.robot")
    public DataSource setDataSource() {
        return new DruidDataSource();
    }

    @Bean(name = "robotTransactionManager")
    public DataSourceTransactionManager setTransactionManager(@Qualifier("robotDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "robotSqlSessionFactory")
    public SqlSessionFactory setSqlSessionFactory(@Qualifier("robotDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);

        // spring boot2.0.0暂时不支持分页,以后可能会支持
        //bean.setPlugins(new PageInterceptor[]{});

        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/robot/*.xml"));
        
        // 开启开启驼峰命名转换
        bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        return bean.getObject();
    }

    @Bean(name = "robotSqlSessionTemplate")
    public SqlSessionTemplate setSqlSessionTemplate(@Qualifier("robotSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
spring:
  datasource:
    robot:
      name: db-robot
      type: com.alibaba.druid.pool.DruidDataSource
      driver-class-name: com.mysql.jdbc.Driver
      initialize: false
      url: jdbc:mysql://localhost:3306/robot?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull
      username: root
      password: 123456

猜你喜欢

转载自my.oschina.net/u/3777515/blog/1794769
今日推荐