千家信息网

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

发表于:2025-01-23 作者:千家信息网编辑
千家信息网最后更新 2025年01月23日,这篇文章将为大家详细讲解有关如何实现在Springboot中集成Mybatis和Druid,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。实现在Springboot中
千家信息网最后更新 2025年01月23日如何实现在Springboot中集成Mybatis和Druid

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

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

        org.springframework.boot        spring-boot-starter-parent        2.0.0.RELEASE         

1,引入需要的依赖

        com.alibaba        druid        1.1.8          org.mybatis          mybatis-spring          1.3.2          org.mybatis          mybatis          3.4.6            org.springframework            spring-jdbc        com.github.pagehelper        pagehelper        5.1.4

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配置方式的 @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 properties = new HashMap();        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 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监控

@Configurationpublic 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"这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

0