zoukankan      html  css  js  c++  java
  • springboot(二) 设置Mybatis和Spring Boot整合

    MybatisSpring Boot的整合有两种方式

    第一种使用mybatis官方提供的Spring Boot整合包实现地址https://github.com/mybatis/spring-boot-starter

    第二种使用mybatis-spring整合的方式也就是我们传统的方式

    这里我们推荐使用第二种因为这样我们可以很方便的控制Mybatis的各种配置

    首先创建一个Mybatis的配置类

     

    代码

    import javax.sql.DataSource;

    import org.mybatis.spring.SqlSessionFactoryBean;

    import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;

    import org.springframework.context.annotation.Bean;

    import org.springframework.context.annotation.Configuration;

    import org.springframework.core.io.Resource;

    import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

    import org.springframework.core.io.support.ResourcePatternResolver;

    @Configuration

    public class MyBatisConfig {

        @Bean

        @ConditionalOnMissingBean //当容器里没有指定的Bean的情况下创建该对象

        public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {

            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

            // 设置数据源

            sqlSessionFactoryBean.setDataSource(dataSource);

            // 设置mybatis的主配置文件

            ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

            Resource mybatisConfigXml = resolver.getResource("classpath:mybatis/mybatis-config.xml");

            sqlSessionFactoryBean.setConfigLocation(mybatisConfigXml);

            // 设置别名包

            sqlSessionFactoryBean.setTypeAliasesPackage("com.taotao.cart.pojo");

            return sqlSessionFactoryBean;

        }

    }

    然后,创建Mapper接口的扫描类MapperScannerConfig:

     

    代码

    import org.mybatis.spring.mapper.MapperScannerConfigurer;

    import org.springframework.boot.autoconfigure.AutoConfigureAfter;

    import org.springframework.context.annotation.Bean;

    import org.springframework.context.annotation.Configuration;

    @Configuration

    @AutoConfigureAfter(MyBatisConfig.class) //保证在MyBatisConfig实例化之后再实例化该类

    public class MapperScannerConfig {

        

        // mapper接口的扫描器

        @Bean

        public MapperScannerConfigurer mapperScannerConfigurer() {

            MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();

            mapperScannerConfigurer.setBasePackage("com.taotao.cart.mapper");

            return mapperScannerConfigurer;

        }

    }

    本人开发小白,所写随笔有转发、有心得、随笔、所见问题、或者感觉不错的东西,希望能帮助他人,同时也相当给自己方便!(未来及标明出处,望原作者以及读者见谅海涵!一切为了能解决问题。。。。)
  • 相关阅读:
    python连接数据库异步存储
    pythonscrapy之MySQL同步存储
    头有点大
    scrapy反爬虫
    《猫抓老鼠》
    Linux下系统监控工具nmon
    探索式测试学习资料
    开始探索式测试学习之前的思考
    Software Quality Characteristics 软件质量特性
    自动化测试整理 STAF/STAX & Robot Framework
  • 原文地址:https://www.cnblogs.com/chengjiao/p/9633588.html
Copyright © 2011-2022 走看看