温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何实现在Springboot中集成Mybatis和Druid

发布时间:2021-12-15 11:49:16 来源:亿速云 阅读:171 作者:小新 栏目:软件技术

这篇文章将为大家详细讲解有关如何实现在Springboot中集成Mybatis和Druid,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

实现在Springboot中集成Mybatis和Druid。其中使用的为spring-boot-starter-parent如下:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
</parent>

1,引入需要的依赖

<dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.8</version>
</dependency>
<dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis-spring</artifactId>
          <version>1.3.2</version>
</dependency>
<dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.4.6</version>
</dependency>
<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>5.1.4</version>
</dependency>

2,application.yml中配置数据源信息

spring: 
  datasource: 
    master:
      driverClassName: oracle.jdbc.OracleDriver
      url: jdbc:oracle:thin:@192.168.30.150:1521:orcl
      username: ioss_sqm
      password: ioss_sqm

3,创建用于封装数据源配置信息的对象DruidPropConfig

public class DruidPropConfig {
    private String url ;
    private String driverClassName ;
    private String username ;
}

4,创建用于判断是否需要创建数据源的Condition对象

public class MasterDataSourceCondition implements Condition {

    @Override
    public boolean matches(ConditionContext context, AnnotatedTypeMetadata arg1) {
        if(!context.getEnvironment().containsProperty("spring.datasource.master.url")){
            return false ;
        }
        if(!context.getEnvironment().containsProperty("spring.datasource.master.driverClassName")){
            return false ;
        }
        if(!context.getEnvironment().containsProperty("spring.datasource.master.username")){
            return false ;
        }
        if(!context.getEnvironment().containsProperty("spring.datasource.master.password")){
            return false ;
        }
        String url = context.getEnvironment().getProperty("spring.datasource.master.url") ;
        String driverClassName = context.getEnvironment().getProperty("spring.datasource.master.driverClassName") ;
        String username = context.getEnvironment().getProperty("spring.datasource.master.username") ;
        String password = context.getEnvironment().getProperty("spring.datasource.master.password") ;
        if(StringUtils.isNotBlank(url) && StringUtils.isNotBlank(driverClassName) 
                && StringUtils.isNotBlank(username)&& StringUtils.isNotBlank(password)){
            return true ;
        }
        return false;
    }
}

5,配置数据源

@Configuration 
@EnableTransactionManagement // 启注解事务管理,等同于xml配置方式的 <tx:annotation-driven />
@Conditional(MasterDataSourceCondition.class)
@MapperScan(basePackages = "com.ultrapower.ioss.cmnet.linksync.mapper", sqlSessionTemplateRef="sqlSessionTemplate")
public class MasterDataSourceCfg{

    private Logger log = LoggerFactory.getLogger(MasterDataSourceCfg.class) ;

    public PageInterceptor pageHelper() {
        PageInterceptor pageHelper = new PageInterceptor();
        Properties properties = new Properties();
        properties.setProperty("offsetAsPageNum", "true");
        properties.setProperty("rowBoundsWithCount", "true");
        properties.setProperty("offsetAsPageNum", "true");
        properties.setProperty("pageSizeZero", "true");
        properties.setProperty("reasonable", "true");
        properties.setProperty("autoRuntimeDialect", "true");
        // properties.setProperty("params","pageNum=pageNum;pageSize=pageSize");
        pageHelper.setProperties(properties);
        return pageHelper;
    }

    @Primary
    @Bean(name = "datasourceConfig")
    @ConfigurationProperties(prefix="spring.datasource.master")
    public DruidPropConfig datasourceConfig(){
        return new DruidPropConfig();
    }

    /**
     * 主数据库数据源
     * */
    @Primary
    @Bean(name = "dataSource")
    public DataSource dataSource() throws Exception{
        DruidPropConfig config = datasourceConfig();
        if(config == null || config.getDriverClassName() == null){
            throw new Exception("slave datasource 数据源需要配置." + config.toString());
        }
        /*
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(config.getDriverClassName());
        dataSource.setUrl(config.getUrl());
        dataSource.setUsername(config.getUsername());
        dataSource.setPassword(config.getPassword());
        dataSource.setConnectionErrorRetryAttempts(5);
        return dataSource;
        */
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put(DruidDataSourceFactory.PROP_DRIVERCLASSNAME, config.getDriverClassName());
        properties.put(DruidDataSourceFactory.PROP_URL, config.getUrl());
        properties.put(DruidDataSourceFactory.PROP_USERNAME, config.getUsername());
        properties.put(DruidDataSourceFactory.PROP_PASSWORD, config.getPassword());
        // 添加统计、SQL注入、日志过滤器
        properties.put(DruidDataSourceFactory.PROP_FILTERS, "stat,wall,log4j2");
        // sql合并,慢查询定义为5s
        properties.put(DruidDataSourceFactory.PROP_CONNECTIONPROPERTIES, "druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000");
        return DruidDataSourceFactory.createDataSource(properties);
    }

    @Primary
    @Bean(name = "sqlSessionFactory")
    @ConditionalOnBean(name = "dataSource") // 仅仅在当前上下文中存在某个对象时,才会实例化一个Bean
    public SqlSessionFactory sqlSessionFactoryBean(@Qualifier("dataSource") DataSource dataSource) {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        //bean.setObjectWrapperFactory(new MapWrapperFactory());
        bean.setDataSource(dataSource);
        // bean.setPlugins(new Interceptor[] {
        // pageHelper(),sqlPrintInterceptor() });
        bean.setPlugins(new Interceptor[] { pageHelper() });
        // 添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            List<Resource> resources = new ArrayList<>();
            resources.addAll(Arrays.asList(resolver.getResources("classpath*:com/ultrapower/ioss/**/mapper/**/*.xml")));
            resources.addAll(Arrays.asList(resolver.getResources("classpath:mapper/**/*.xml")));
            bean.setMapperLocations(resources.toArray(new Resource[resources.size()]));
            // 设置mybatis configuration 扫描路径
            // bean.setConfigLocation(resolver.getResource("classpath:mybatis-config.xml"));
            return bean.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Primary
    @Bean("sqlSessionTemplate")
    @ConditionalOnBean(name = "sqlSessionFactory")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Primary
    @ConditionalOnBean(name = "dataSource")
    @Bean(name = "transactionManager")
    public PlatformTransactionManager transactionManager(@Qualifier("dataSource") DataSource dataSource) {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(dataSource);
        return dataSourceTransactionManager;
    }
}

6,配置Durid监控

@Configuration
public class DruidConfiguration {

    @Bean
    public ServletRegistrationBean druidServlet() {
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        servletRegistrationBean.setServlet(new StatViewServlet());
        servletRegistrationBean.addUrlMappings("/druid/*");
        // IP白名单
        //servletRegistrationBean.addInitParameter("allow", "192.168.2.25,127.0.0.1");
        // IP黑名单(共同存在时,deny优先于allow)
        //servletRegistrationBean.addInitParameter("deny", "192.168.1.100");
        // 控制台管理用户
        servletRegistrationBean.addInitParameter("loginUsername", "admin");
        servletRegistrationBean.addInitParameter("loginPassword", "admin");
        // 是否能够重置数据 禁用HTML页面上的“Reset All”功能
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean filterRegistrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}

关于“如何实现在Springboot中集成Mybatis和Druid”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI