深入浅出SpringBoot系列--与mybatis集成

[TOC]
本文主要介绍下常见的spring boot与mybatis集成方案,下面简单介绍下集成步骤。spring boot的集成方案不同于传统的spring mvc,基本上是零配置;这个方案中只有数据库连接字符串还放在配置文件中,后续其实可以在阿波罗配置,实现零配置。

集成步骤
1.POM文件需要引入以下相关的jar:

<!-- mybatis配置相关 begin -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.0.0</version>
    </dependency>


    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.0.26</version>
    </dependency>

<!-- mybatis配置相关 end -->       

2.自定义Mybatis注解类:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyBatisRepository {
}

注入mapperScannerConfigurer

@Configuration
@AutoConfigureAfter(DataSourceConfiguration.class)
public class MyBatisMapperScannerConfig {

    /**
     * 注入mapperScannerConfigurer
     * @return
     * @throws Exception
     */
    @Bean(name = "mapperScannerConfigurer")
    public MapperScannerConfigurer getMapperScannerConfigurer() throws Exception {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
        mapperScannerConfigurer.setBasePackage("com.happy.springboot.service.dao");
        mapperScannerConfigurer.setAnnotationClass(MyBatisRepository.class);
        return mapperScannerConfigurer;
    }
}

3.新建德鲁伊数据源,注入到sessionFatory和事务管理器中。

@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
public class DataSourceConfiguration implements TransactionManagementConfigurer {

    @Bean(name = "masterDataSource", initMethod = "init", destroyMethod = "close")
    @Qualifier("masterDataSource")
    @ConfigurationProperties(prefix = "spring.dataSource.happyboot")
    public DataSource getMasterDataSource() {
        return createDefaultDruidDataSource();
    }
    public DruidDataSource createDefaultDruidDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setMaxWait(60000l);
        druidDataSource.setMaxActive(20);
        druidDataSource.setInitialSize(1);
        druidDataSource.setMinIdle(1);
        druidDataSource.setTimeBetweenEvictionRunsMillis(3000l);
        druidDataSource.setMinEvictableIdleTimeMillis(300000l);
druidDataSource.setConnectionProperties("druid.stat.slowSqlMillis=3000");
        druidDataSource.setValidationQuery("SELECT 'x'");
        druidDataSource.setTestWhileIdle(true);
        druidDataSource.setTestOnBorrow(false);
        druidDataSource.setTestOnReturn(false);
        return druidDataSource;
    }
    /**
     * 注入sqlSessionFactory
     * 
     * @return
     * @throws Exception
     */
    @Bean(name = "sqlSessionFactory")
    public SqlSessionFactory getinvestListingSqlSessionFactory() throws Exception {
        String configLocation = "classpath:/conf/mybatis/configuration.xml";
        String mapperLocation = "classpath*:/com/happy/springboot/service/dao/*/*Mapper.xml";
        SqlSessionFactory sqlSessionFactory = createDefaultSqlSessionFactory(getMasterDataSource(), configLocation,
                mapperLocation);
        return sqlSessionFactory;
    }

    /**
     * 创建sqlSessionFactory
     * @param dataSource
     * @param configLocation
     * @param mapperLocation
     * @return
     * @throws Exception
     */
    public SqlSessionFactory createDefaultSqlSessionFactory(DataSource dataSource, String configLocation,
            String mapperLocation) throws Exception {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setTypeAliasesPackage("com.happy.springboot.service.dao.model.entity");
        factory.setDataSource(dataSource);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
factory.setConfigLocation(resolver.getResource(configLocation));
        SqlSessionFactory target = null;
        try {
factory.setMapperLocations(resolver.getResources(mapperLocation));
            target = (SqlSessionFactory) factory.getObject();
        target.getConfiguration().setDefaultStatementTimeout(30);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return target;
    }

    /**
     * 事务管理
     * @return
     */
    @Bean(name = "txManager")
    public PlatformTransactionManager txManager() {
        return new DataSourceTransactionManager(getMasterDataSource());
    }
    @Override
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return txManager();
    }

}

数据库相关配置文件:
spring:
  dataSource:
    happyboot:
      driverClassName: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/happy_springboot?characterEncoding=utf8&useSSL=true
      username: root
      password: admin

4.单元测试

public class UserInfoTestCase extends BaseService {
    @Autowired
    protected ApplicationContext ctx;
    @Before
    public void init() {
        // 注入上下文工具类 
            GlobalApplicationContext.getInstance().setApplicationContext(ctx);
    }
    @Autowired
    UserInfoMapper userInfoMapper;
    @Test
    public void getUserInfo() {
        System.err.println(userInfoMapper.selectByPrimaryKey(1l));
    }
}

测试结果:
UserInfo [id=1, userId=1233, userName=张三, insertTime=Sun Jul 15 09:25:06 CST 2018, updateTime=Sun Jul 15 09:25:06 CST 2018, isActive=true]

具体代码(包括建表脚本)参见:
https://github.com/jasonhsu2017/happy-springboot.git

猜你喜欢

转载自blog.csdn.net/xuxian6823091/article/details/81039886