SpringBoot集成mybatis(配置通用mapper)并且使用druid作为数据库连接池

主要包括:

  1. springBoot集成mybatis框架
  2. 使用配置mybatis框架的通用mapper功能
  3. 使用阿里的druid作为数据库连接池
  4. 利用swagger进行接口测试

一.先创建一个springBoot的maven工程,这个小伙伴肯定都会

二.引入相关依赖


        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-jdbc
        
        
        
            mysql
            mysql-connector-java
            runtime
        
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
        
            commons-lang
            commons-lang
            2.5
        

        
        
            com.alibaba
            druid
            1.0.26
        
        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.0
        
        
        
            tk.mybatis
            mapper-spring-boot-starter
            2.1.5
        
        
        
            com.github.pagehelper
            pagehelper
            4.1.6
        
        
        
            io.springfox
            springfox-swagger2
            2.6.0
        
        
            io.springfox
            springfox-swagger-ui
            2.6.0
        

三.配置mybatis

@Configuration
public class MybatisConfig {

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean factroy = new SqlSessionFactoryBean();
        factroy.setDataSource(dataSource);
        VFS.addImplClass(SpringBootVFS.class);
        factroy.setTypeAliasesPackage("com.school.project.entity");
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        factroy.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
        //配置分页插件
        PageHelper pageHelper = new PageHelper();
        Properties properties = new Properties();
        properties.setProperty("pageSizeZero", "true"); //分页尺寸为0时候查询所有记录不再执行分页
        properties.setProperty("reasonable", "true"); //页码<=查询第一页 ,页码>=总页数查询最后一页
        properties.setProperty("supportMethodsArguments", "true"); // 支持通过mapper接口参数传递分页参数
        pageHelper.setProperties(properties);
        //添加插件
        factroy.setPlugins(new Interceptor[]{pageHelper});
        try {
            //开启驼峰命名转换
            factroy.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
            return factroy.getObject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
        mapperScannerConfigurer.setBasePackage("com.school.project.dao.mapper"); //存放mapper接口的包路径
        //配置通用mapper
        Properties properties = new Properties();
        properties.setProperty("mappers","com.school.project.dao.base.Mapper"); //mapper插件基础接口的全限定明 此包下的Mapper 继承 BaseMapper,ConditionMapper,IdsMapper,InsertListMapper 接口,如需其他接口可以参考官方文档。
        properties.setProperty("notEmpty", "false");
        properties.setProperty("IDENTITY", "MYSQL");
        mapperScannerConfigurer.setProperties(properties);
        return mapperScannerConfigurer;

    }

}

四.开启swagger

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                    .title("学生管理系统")
                    .build())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.school.project.controller"))
                .paths(PathSelectors.any())
                .build();
    }

}

配置好这个在浏览器上访问localhost:8899/student/swagger-ui.html 即可访问

五.配置文件里的一些配置

server:
  port: 8899
  servlet:
    context-path: /student

spring:
  profiles:
    active: dev
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root
    url: jdbc:mysql://192.168.109.66:3306/learn?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=UTC
    type: com.alibaba.druid.pool.DruidDataSource
    # 连接池配置
    druid:
      #启动程序时,在连接池中初始化多少个连接
      initialSize: 5
      #最小连接池数量
      minIdle: 5
      ##连接池中最多支持多少个活动会话
      maxActive: 20
      # 获取连接时最大等待时间,单位毫秒
      maxWait: 60000
      # 有两个含义:
        #1) Destroy线程会检测连接的间隔时间
        # 2) testWhileIdle的判断依据,详细看testWhileIdle属性的说明
      timeBetweenEvictionRunsMillis: 60000
      # Destory线程中如果检测到当前连接的最后活跃时间和当前时间的差值大于,minEvictableIdleTimeMillis,则关闭当前连接
      minEvictableIdleTimeMillis: 300000
      #用来检测连接是否有效的sql,要求是一个查询语句。
      validationQuery: SELECT 1 FROM DUAL
      #建议配置为true,不影响性能,并且保证安全性。
       #申请连接的时候检测,如果空闲时间大于
       #timeBetweenEvictionRunsMillis,
       #执行validationQuery检测连接是否有效。
      testWhileIde: true
      #申请连接时执行validationQuery检测连接是否有效,做了这个配置会影响性能
      testOnBorrow: false
      #归还连接时执行validationQuery检测连接是否有效,做了这个配置会影响性能
      testOnReturn: false
      # 是否缓存preparedStatement,也就是PSCache mql5.5以上建议开启
      poolPreparedStatements: true
     # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
      filters: stat,wall,log4j2
      maxPoolPreparedStatementPerConnectionSize: 20
      # 合并多个DruidDataSource的监控数据
      useGlobalDataSourceStat: true
      # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
  mvc:
    view:
      prefix: /jsp/
      suffix: .jsp
  jpa:
    hibernate:
      ddl-auto: update

logging:
  level:
    org.springframework: INFO
  file: /home/student/student.log

jpa的配置到时候可以通过注解生成表,第一次ddl设置成create,以后改成update

六.druid的配置文件

@Configuration
public class DruidConfiguration {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDateSource(){
        DruidDataSource druidDataSource =new DruidDataSource();
        return druidDataSource;
    }
    //配置一个druid的监控
    //配置一个后台的Servlet
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean =new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
        Map initParams =new HashMap<>();
        initParams.put("loginUsername","admin");
        initParams.put("loginPassword","123456");
        initParams.put("allow",""); //默认是允许所有访问
        initParams.put("deny","192.168.15.21");
        bean.setInitParameters(initParams);
        return bean;
    }

    //2、配置一个web监控的filter
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        Map initParams = new HashMap<>();
        initParams.put("exclusions","*.js,*.css,/druid/*");
        bean.setInitParameters(initParams);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return  bean;
    }

启动类上加上

@ServletComponentScan注解

配置好后通过浏览器输入localhost:8899/student/druid就可访问druid的监控台

七.配置基础mapper

public interface Mapper extends
        BaseMapper,
        ConditionMapper,
        IdsMapper,
        InsertListMapper

{
}

做完以上配置就可以写对应的entity、service、controller、启动项目进行测试使用了。

你可能感兴趣的:(springBoot)