SpringBoot 整合Mybatis Plus + Oracle

1、引入mybatis plus 依赖。

   

   

    <!—配置事务管理-->

    <dependency>

      <groupId>org.springframework.boot</groupId>

      <artifactId>spring-boot-starter-jdbc</artifactId>

    </dependency>

      

    <!--mybatis-plus  依赖-->

    <dependency>

      <groupId>com.baomidou</groupId>

      <artifactId>mybatis-plus</artifactId>

      <version>3.0.6</version>

    </dependency>

      

    <!--oracle 驱动-->

    <dependency>

      <groupId>com.oracle</groupId>

      <artifactId>ojdbc8</artifactId>

      <version>1.0</version>

    </dependency>

      

    <!-- druid 连接池-->

    <dependency>

      <groupId>com.alibaba</groupId>

      <artifactId>druid</artifactId>

      <version>1.1.10</version>

    </dependency>

   

   

2、配置application.yml文件。

spring:

  # 配置oracle连接数据

datasource:

    type: com.alibaba.druid.pool.DruidDataSource

    url: jdbc:oracle:thin:@192.168.2.128:1521:abc

    username: jarisignal

    password: jarisignal

  #配置连接池

driverClassName: oracle.jdbc.driver.OracleDriver

   

    # 配置初始化大小、最小、最大,通常来说,只需要修改initialSize、minIdle、maxActive

    initialSize: 5

    minIdle: 5

    maxActive: 20

    # 配置获取连接等待超时的时间

    maxWait: 60000

    # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒

    timeBetweenEvictionRunsMillis: 60000

    # 配置一个连接在池中最小生存的时间,单位是毫秒

    minEvictableIdleTimeMillis: 300000

    validationQuery: SELECT 1 FROM DUAL

    testWhileIdle: true

    testOnBorrow: false

    testOnReturn: false

    # 打开PSCache,并且指定每个连接上PSCache的大小,如果用Oracle,则把poolPreparedStatements配置为true,mysql可以配置为false。分库分表较多的数据库,建议配置为false

    poolPreparedStatements: false

    maxPoolPreparedStatementPerConnectionSize: 20

    # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙

    filters: stat,log4j,config

   

3、编写@Configuration配置文件。

在ssm中我们需要在application.xml文件中编写 <bean> 来生成 SqlSessionFactory 被spring管理 和 扫描路径下的mapper文件。

/**

* 版      权 :  lyg.com

* 包      名 : com.lyg.config

* 描      述 :  MybatisConfig

* 创建 时 间:  1970/01/01

* <p>

*

* @author :  

*/

@Configuration//声明为配置类

@MapperScan(basePackages = {"com.lyg.rtt.dao"})//扫描该包下的文件

@EnableTransactionManagement//开启事务管理

@Slf4j//日志

public class MyBatisConfig {

    //DataSourceConfig类读取application.yml文件总的 dataSource 配置

    @javax.annotation.Resource

    private DataSourceConfig dataSourceConfig;

    //读取 application.yml文件总的 Druid连接池 配置

    private DruidDataSource dataSource = null;

   

    /**

     * 初始化数据源

     * <p>

     * 创建人:    

     * 创建日期:   1970-01-01

     * 描述    :    初始化数据源

     *

     * @param

     * @return DataSource

     * @throws Exception

     */

    @Bean(name = "dataSource")

    public DataSource dataSource() throws Exception {

   

        log.info("初始化数据源 dataSourceConfig = {}", dataSourceConfig);

   

        dataSource = new DruidDataSource();

        //链接地址

        dataSource.setUrl(dataSourceConfig.getUrl());

        //数据库用户名

        dataSource.setUsername(dataSourceConfig.getUsername());

        //数据库密码

        dataSource.setPassword(dataSourceConfig.getPassword());

        //配置初始化

        dataSource.setInitialSize(dataSourceConfig.getInitialSize());

        dataSource.setMinIdle(dataSourceConfig.getMinIdle());

        dataSource.setMaxActive(dataSourceConfig.getMaxActive());

        //获取连接等待超时的时间

        dataSource.setMaxWait(dataSourceConfig.getMaxWait());

        //间隔多久才进行一次检测

        dataSource.setTimeBetweenEvictionRunsMillis(dataSourceConfig.getTimeBetweenEvictionRunsMillis());

        //接在池中最小生存的时间

        dataSource.setMinEvictableIdleTimeMillis(dataSourceConfig.getMinEvictableIdleTimeMillis());

        //validationQuery

        String validationQuery = dataSourceConfig.getValidationQuery();

        if (null != validationQuery && !"".equals(validationQuery)) {

            dataSource.setValidationQuery(validationQuery);

        }

        //testWhileIdle

        dataSource.setTestWhileIdle(dataSourceConfig.isTestWhileIdle());

        //testOnBorrow

        dataSource.setTestOnBorrow(dataSourceConfig.isTestOnBorrow());

        //testOnReturn

        dataSource.setTestOnReturn(dataSourceConfig.isTestOnReturn());

        //分库分表较多的数据库,建议配置为false

        if (dataSourceConfig.isPoolPreparedStatements()) {

            dataSource.setMaxPoolPreparedStatementPerConnectionSize(dataSourceConfig.getMaxPoolPreparedStatementPerConnectionSize());

        }

        log.info("成功创建dataSource,dataSource = {}", dataSource);

        return dataSource;

    }

   

   

    /**

     * 关闭数据源

     * <p>

     * 创建人:    

     * 创建日期:   1970-01-01

     * 描述    :    关闭数据源

     *

     * @param

     * @return

     * @throws

     */

    //@PreDestroy 关闭spring容器后释放一些资源

    @PreDestroy

    public void close() {

        if (dataSource != null) {

            dataSource.close();

            log.info("成功关闭数据源");

        }

    }

   

   

    /**

     * 创建sqlSessionFactory

     * <p>

     * 创建人:    

     * 创建日期:   1970-01-01

     * 描述    :    创建sqlSessionFactory

     *

     * @param

     * @return SqlSessionFactory

     * @throws Exception

     */

    @Bean

    public SqlSessionFactory sqlSessionFactory() throws Exception {

   

        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();

   

   

        // mybatisPlus相关配置

        GlobalConfig globalConfig = new GlobalConfig();

        // 配置逻辑删除参数

        GlobalConfig.DbConfig dbConfig = new GlobalConfig.DbConfig();

        // 已删除标识

        dbConfig.setLogicDeleteValue("0");

        // 正常

        dbConfig.setLogicNotDeleteValue("1");

        globalConfig.setDbConfig(dbConfig);

        // 逻辑删除组件  =>>>tyq

        globalConfig.setSqlInjector(new LogicSqlInjector());

        sqlSessionFactoryBean.setGlobalConfig(globalConfig);

        //数据源

        sqlSessionFactoryBean.setDataSource(dataSource());

   

        //设置SQL打印

        sqlSessionFactoryBean.setPlugins(new Interceptor[]{

                new PerformanceInterceptor().setFormat(Boolean.TRUE),

                // 配置乐观锁插件 =>>> tyq

                new OptimisticLockerInterceptor()

        });

   

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

   

        //加载 指定包下的源文件,主要是扫描mapper.xml

        Resource[] resources_core = resolver.getResources("classpath*:com/lyg/rtt/dao/mapper/*Mapper.xml");

   

        Resource[] resources = ArrayUtils.addAll(resources_core);

   

        //设置mapperLocations

        sqlSessionFactoryBean.setMapperLocations(resources);

   

        //驼峰

        sqlSessionFactoryBean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);

   

        log.info("成功创建sqlSessionFactory,sqlSessionFactoryBean = {}", sqlSessionFactoryBean);

   

        return sqlSessionFactoryBean.getObject();

   

    }

   

    /**

     * 配置事务管理器

     * <p>

     * 创建人:    

     * 创建日期:   1970-01-01

     * 描述    :    配置事务管理器

     *

     * @param

     * @return DataSourceTransactionManager

     * @throws Exception

     */

    @Bean(name = "transactionManager")

    @Primary

    public DataSourceTransactionManager transactionManager() throws Exception {

        log.info("开始配置事务管理器");

        return new DataSourceTransactionManager(dataSource);

    }

   

}

   

PS:

DataSourceConfig.class的配置

/**

* 版      权 :  lyg.com

* 包      名 : com.lyg.config

* 描      述 :  DataSourceConfig

* 创建 时 间:  1970/01/01

* <p>

*

* @author :  

*/

@Getter

@Setter

@ToString

@Configuration

@ConfigurationProperties(prefix = "spring.datasource")

public class DataSourceConfig {

   

    /**

     * 数据源类型

     **/

    private String type;

    /**

     * 数据库驱动

     **/

    private String driverClassName;

    /**

     * 链接地址

     **/

    private String url;

    /**

     * 数据库用户名

     **/

    private String username;

    /**

     * 数据库密码

     **/

    private String password;

    /**

     * 配置初始化

     **/

    private Integer initialSize ;

    /**

     * 配置初始化

     **/

    private Integer minIdle ;

    /**

     * 配置初始化

     **/

    private Integer maxActive;

    /**

     * 获取连接等待超时的时间

     **/

    private Long maxWait;

    /**

     * 间隔多久才进行一次检测

     **/

    private Long timeBetweenEvictionRunsMillis;

    /**

     * 接在池中最小生存的时间

     **/

    private Long minEvictableIdleTimeMillis;

    /**

     * validationQuery

     **/

    private String validationQuery;

    /**

     * testWhileIdle

     **/

    private boolean testWhileIdle;

    /**

     * testOnBorrow

     **/

    private boolean testOnBorrow;

    /**

     * testOnReturn

     **/

    private boolean testOnReturn;

    /**

     * poolPreparedStatements

     **/

    private boolean poolPreparedStatements;

    /**

     * 分库分表较多的数据库,建议配置为false

     **/

    private Integer maxPoolPreparedStatementPerConnectionSize;

    /**

     * 监控统计拦截的filters

     **/

    private String filters;

   

    /**

     * connectionProperties

     **/

    private String connectionProperties;

   

}

   

     ②如果只是 如上 配置 ,可能会出现项目能启动,但是sql语句执行报错。原因:编译过程中mapper.xml文件没有编译进去。所以还需要在pom.xml文件中加入下配置:

<build>

    <resources>

   

      <resource>

        <directory>src/main/java/</directory>

        <includes>

          <include>**/*.properties</include>

          <include>**/*.xml</include>

          <include>**/*.yml</include>

        </includes>

        <excludes>

          <exclude>**/.git/*</exclude>

          <exclude>**/.svn/*</exclude>

        </excludes>

      </resource>

      <resource>

        <directory>src/main/resources/</directory>

        <includes>

          <include>**/*.properties</include>

          <include>**/*.xml</include>

          <include>**/*.css</include>

          <include>**/*.js</include>

          <include>**/*.yml</include>

          <include>**/*.ftl</include>

          <include>**/**</include>

        </includes>

        <excludes>

          <exclude>**/.git/*</exclude>

          <exclude>**/.svn/*</exclude>

        </excludes>

      </resource>

    </resources>

</build>

 

posted @ 2020-11-21 14:42  黑质白章  阅读(10294)  评论(0编辑  收藏  举报