mybatisplus配置

pom文件引入依赖

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.2</version>
</dependency>

application.yaml

spring:
  datasource:
    remote-sqlserver1:
     		...
    remote-xugu1:
            ...
    remote-xugu2:
            ...
    remote-xugu3:
      username: SYSDBA
      password: SYSDBA
      driver-class-name: com.xugu.cloudjdbc.Driver
      url: jdbc:xugu://ip:port/SYSTEM?time_zone=GMT-8:00

  druid:
    initial-size: 10 # 初始化时建立物理连接的个数。初始化发生在显示调用init方法,或者第一次getConnection时
    min-idle: 10 # 最小连接池数量
    maxActive: 200 # 最大连接池数量
    maxWait: 60000 # 获取连接时最大等待时间,单位毫秒。配置了maxWait之后,缺省启用公平锁,并发效率会有所下降,如果需要可以通过配置
    timeBetweenEvictionRunsMillis: 60000 # 关闭空闲连接的检测时间间隔.Destroy线程会检测连接的间隔时间,如果连接空闲时间大于等于minEvictableIdleTimeMillis则关闭物理连接。
    minEvictableIdleTimeMillis: 300000 # 连接的最小生存时间.连接保持空闲而不被驱逐的最小时间
    validationQuery: SELECT 1 FROM DUAL # 验证数据库服务可用性的sql.用来检测连接是否有效的sql 因数据库方言而差, 例如 oracle 应该写成 SELECT 1 FROM DUAL
    testWhileIdle: true # 申请连接时检测空闲时间,根据空闲时间再检测连接是否有效.建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRun
    testOnBorrow: false # 申请连接时直接检测连接是否有效.申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
    testOnReturn: false # 归还连接时检测连接是否有效.归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
    poolPreparedStatements: true # 开启PSCache
    maxPoolPreparedStatementPerConnectionSize: 20 #设置PSCache值
    connectionErrorRetryAttempts: 3 # 连接出错后再尝试连接三次
    breakAfterAcquireFailure: true # 数据库服务宕机自动重连机制
    timeBetweenConnectErrorMillis: 300000 # 连接出错后重试时间间隔
    asyncInit: true # 异步初始化策略
    remove-abandoned: true # 是否自动回收超时连接
    remove-abandoned-timeout: 1800 # 超时时间(以秒数为单位)
    transaction-query-timeout: 6000 # 事务超时时间
    filters: stat,wall,log4j2
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
    web-stat-filter:
      enabled: true
      url-pattern: "/*"
      exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"

mybatisplus配置类

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.meteorological.mapper.remote.xugu3", sqlSessionFactoryRef = "remoteXuGu3SqlSessionFactory")
public class RemoteXuGu3DatasourceConfig {
    /**
     * 新增分页拦截器,并设置数据库类型为mysql
     */
    @Bean(name = "mybatisPlusInterceptor")
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    @Bean(name = "remoteXuGu3DatasourceProperties")
    @ConfigurationProperties(prefix = "spring.datasource.remote-xugu3")
    public DataSourceProperties remoteXuGu3DatasourceProperties(){
        return new DataSourceProperties();
    }

    @Bean(name = "remoteXuGu3Datasource")
    public DataSource remoteXuGu3Datasource(@Qualifier("remoteXuGu3DatasourceProperties") DataSourceProperties dataSourceProperties) {
        return dataSourceProperties.initializeDataSourceBuilder().build();
    }

    @Bean("remoteXuGu3SqlSessionFactory")
    public SqlSessionFactory remoteXuGu3SqlSessionFactory(@Qualifier("remoteXuGu3Datasource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setGlobalConfig(new GlobalConfig().setBanner(false).setMetaObjectHandler(new MybatisPlusAutoFillConfig()));
        //设置mybatis-plus分页插件
        bean.setPlugins(mybatisPlusInterceptor());
        // 设置标准控制台输出SQL(开发环境中使用)
        {
            MybatisConfiguration mybatisConfiguration = new MybatisConfiguration();
            mybatisConfiguration.setLogImpl(StdOutImpl.class);
            bean.setConfiguration(mybatisConfiguration);
        }
        // 配置Mapper.xml映射文件匹配路径
        //bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/remote/xugu3/*.xml"));
        return bean.getObject();
    }

    @Bean("remoteXuGu3SqlSessionTemplate")
    public SqlSessionTemplate remoteXuGu3SqlSessionTemplate(@Qualifier("remoteXuGu3SqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

mapper文件

package com.meteorological.mapper.remote.xugu3;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.meteorological.entity.api.ApiElementsDO;
import org.springframework.stereotype.Repository;

@Repository
public interface IApiElementsMapper extends BaseMapper<ApiElementsDO> {
}

DO实体类

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.*;

import java.io.Serializable;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
@TableName("API_ELEMENTS")
public class ApiElementsDO implements Serializable {
  /**
   * id
   */
  @TableId(value = "ID", type = IdType.AUTO)
  private Integer id;
  /**
   * 要素代码
   */
  @TableField(value = "ELEMENT_CODE")
  private String elementCode;
  /**
   * 要素名称
   */
  @TableField(value = "ELEMENT_NAME")
  private String elementName;
  /**
   * 单位
   */
  @TableField(value = "UNIT")
  private String unit;

  @TableField(value = "DATA_CODE")
  private String dataCode;
}

service中引入mapper

@Component
public class TRadar {
    private final IApiElementsMapper apiElementsMapper;

    Log log = LogFactory.getLog(com.meteorological.service.task.TRadar.class);

    @Autowired
    public TRadar(IApiElementsMapper apiElementsMapper) {
        this.apiElementsMapper = apiElementsMapper;
    }

    @PostConstruct
    @Scheduled(cron = "0 5/30 * * * *")
    public void Task100() {
        ApiElementsDO apiElementsDO = apiElementsMapper.selectById(1);
        System.out.println(apiElementsDO);
    }
}

你可能感兴趣的:(MyBatis,java,mybatis)