Spring Cloud + Mybatis配置类设置

spring cloud 继承mybatis相关配置类

/**
 * 该类配置数据源相关属性
 */
@ConfigurationProperties(prefix = DataSourceProperties.DS, ignoreUnknownFields = false)
public class DataSourceProperties {

    //对应配置文件里的配置键
    public final static String DS="application.yml";

    private String driverClassName ="com.mysql.jdbc.Driver";
    
    @Value("${spring.datasource.url}")
    private String url;
    @Value("${spring.datasource.username}")
    private String username;
    @Value("${spring.datasource.password}")
    private String password;
    private int maxActive = 1000;
    private int maxIdle = 100;
    private int minIdle = 8;
    private int initialSize = 10;
    private String validationQuery = "select 1";


    private boolean testOnBorrow = true;

    private boolean testOnReturn = false;

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getMaxActive() {
        return maxActive;
    }

    public void setMaxActive(int maxActive) {
        this.maxActive = maxActive;
    }

    public int getMaxIdle() {
        return maxIdle;
    }

    public void setMaxIdle(int maxIdle) {
        this.maxIdle = maxIdle;
    }

    public int getMinIdle() {
        return minIdle;
    }

    public void setMinIdle(int minIdle) {
        this.minIdle = minIdle;
    }

    public int getInitialSize() {
        return initialSize;
    }

    public void setInitialSize(int initialSize) {
        this.initialSize = initialSize;
    }

    public String getValidationQuery() {
        return validationQuery;
    }

    public void setValidationQuery(String validationQuery) {
        this.validationQuery = validationQuery;
    }

    public boolean isTestOnBorrow() {
        return testOnBorrow;
    }

    public void setTestOnBorrow(boolean testOnBorrow) {
        this.testOnBorrow = testOnBorrow;
    }

    public boolean isTestOnReturn() {
        return testOnReturn;
    }

    public void setTestOnReturn(boolean testOnReturn) {
        this.testOnReturn = testOnReturn;
    }
}
/**
 * mybatis 相关配置
 */
@Configuration
@EnableConfigurationProperties(DataSourceProperties.class)
@MapperScan("com.system.dao")
public class MybatisDataSource {

    private static final Logger logger = LoggerFactory.getLogger(MybatisDataSource.class);

    @Autowired
    private DataSourceProperties dataSourceProperties;

    //mybaits mapper xml搜索路径
    private final static String mapperLocations="classpath:/mapper/*.xml";

    private org.apache.tomcat.jdbc.pool.DataSource pool;

    @Bean(destroyMethod = "close")
    public DataSource dataSource() {
        DataSourceProperties config = dataSourceProperties;
        this.pool = new org.apache.tomcat.jdbc.pool.DataSource();
        this.pool.setDriverClassName(config.getDriverClassName());
        this.pool.setUrl(config.getUrl());
        if (config.getUsername() != null) {
            this.pool.setUsername(config.getUsername());
        }
        if (config.getPassword() != null) {
            this.pool.setPassword(config.getPassword());
        }
        this.pool.setInitialSize(config.getInitialSize());
        this.pool.setMaxActive(config.getMaxActive());
        this.pool.setMaxIdle(config.getMaxIdle());
        this.pool.setMinIdle(config.getMinIdle());
        this.pool.setTestOnBorrow(config.isTestOnBorrow());
        this.pool.setTestOnReturn(config.isTestOnReturn());
        this.pool.setValidationQuery(config.getValidationQuery());
        this.pool.setMaxWait(3600000);
        logger.info("init database conn pool url is {}", config.getUrl());
        return this.pool;
    }

    @PreDestroy
    public void close() {
        if (this.pool != null) {
            this.pool.close();
        }
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());

//        PageHelper pageHelper = new PageHelper();
//        Properties properties = new Properties();
//        properties.setProperty("reasonable", "true");
//        properties.setProperty("supportMethodsArguments", "true");
//        properties.setProperty("returnPageInfo", "check");
//        properties.setProperty("params", "count=countSql");
//        pageHelper.setProperties(properties);
//
//        logger.info("init PageHelper Interceptor");
//        //添加插件
//        sqlSessionFactoryBean.setPlugins(new Interceptor[]{(Interceptor) pageHelper});

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(mapperLocations));
        logger.info("init SqlSessionFactoryBean");
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }
}

 

 

application.yml 配置文件

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

server:
  port: 8764
spring:
  application:
    name: service-system
  datasource:
    url: jdbc:mysql://localhost:3306/test
    username: root
    password:
    driver-class-name: com.mysql.jdbc.Driver

#mybatis config
mybatis:
  typeAliasesPackage: com.system.model
  mapperLocations: classpath:mapper/*.xml

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 构建Spring Cloud MyBatis框架需要以下步骤: 1. 创建Spring Boot项目:创建一个新的Spring Boot项目,可以使用Spring Initializr(https://start.spring.io/)快速创建。 2. 添加依赖:在pom.xml文件中添加以下依赖: ```xml <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-config</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.21</version> </dependency> </dependencies> ``` 说明:上述依赖中,eureka-client和config是用于注册和发现服务和配置中心,mybatis-spring-boot-starter用于集成MyBatis,druid-spring-boot-starter用于配置Druid连接池。 3. 配置数据源:在application.yml或application.properties文件中配置数据源信息和Druid连接池信息。例如: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=utf-8&useSSL=false username: root password: root driver-class-name: com.mysql.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource #以下是Druid连接池相关配置 druid: #启用Druid监控统计功能 stat-view-servlet: enabled: true stat-view-servlet: url-pattern: /druid/* web-stat-filter: enabled: true filter: #配置Druid连接池的相关属性 #initialSize:初始化大小 #minIdle:最小空闲连接数 #maxActive:最大连接数 #maxWait:获取连接等待超时的时间 #timeBetweenEvictionRunsMillis:检查连接池中空闲连接的时间间隔 #minEvictableIdleTimeMillis:连接在池中保持空闲而不被空闲连接回收器线程回收的最长时间 #validationQuery:检查连接是否有效的SQL语句 #testWhileIdle:在空闲时检查连接是否有效 #testOnBorrow:在获取连接时检查连接是否有效 #testOnReturn:在归还连接时检查连接是否有效 initialSize: 5 minIdle: 5 maxActive: 20 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: select 1 from dual testWhileIdle: true testOnBorrow: false testOnReturn: false ``` 4. 配置MyBatis:在application.yml或 ### 回答2: 构建SpringCloud mybatis框架的详细步骤如下: 1. 创建SpringBoot项目:使用Spring Initializr创建一个新的SpringBoot项目,添加所需的依赖,包括SpringCloudMyBatis的依赖。 2. 配置数据库连接:在项目的配置文件application.yml中,配置数据库连接信息,包括数据库URL、用户名、密码等。 3. 创建数据表:根据项目需求,在数据库中创建相应的数据表,并添加测试数据。 4. 定义实体类:创建与数据表对应的实体类,使用注解标记实体类与数据库中的表关联。 5. 创建Mapper接口:在项目中创建Mapper接口,用于定义数据库操作的接口方法。使用注解标记Mapper接口与实体类的关联关系,并定义数据操作的SQL语句。 6. 编写Mapper实现类:创建Mapper接口的实现类,使用MyBatis提供的SQLSessionFactory和Mapper进行数据库的操作。 7. 配置数据源:在SpringBoot的配置文件中,配置数据源的相关信息,包括数据库驱动、连接池等。 8. 配置MyBatis:在SpringBoot的配置文件中,配置MyBatis的相关信息,包括Mapper接口的扫描路径、XML文件的位置等。 9. 配置SpringCloud:使用SpringCloud提供的注解进行微服务的配置,如@EnableDiscoveryClient注解表示注册到注册中心,@EnableFeignClients注解表示使用Feign进行服务间的调用等。 10. 编写Controller:创建Controller类,用于处理请求和响应,并调用Mapper接口中的方法进行数据操作。 11. 启动应用程序:运行SpringBoot的启动类,在控制台查看应用程序的输出日志,确保应用程序正常启动。 12. 测试接口:使用Postman等工具,测试Controller中定义的接口,并验证数据库操作的结果。 通过以上步骤,我们可以构建一个基于SpringCloudMyBatis的框架,实现了微服务架构下的数据库操作功能。 ### 回答3: 构建Spring Cloud Mybatis框架的详细步骤如下: 1. 创建Spring Boot项目:首先,使用Spring Initializr创建一个新的Spring Boot项目。 2. 引入Spring CloudMybatis依赖:在项目的pom.xml文件中添加Spring CloudMybatis的依赖。例如: ``` <dependencies> <!-- Spring Cloud --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <!-- Mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> </dependency> </dependencies> ``` 3. 配置数据源:在application.properties或application.yml文件中配置数据库连接等相关信息。 4. 创建Mybatis Mapper:创建Mybatis Mapper接口,定义数据库操作方法。 5. 创建Mybatis Mapper XML:为每个Mybatis Mapper接口创建对应的XML文件,编写SQL语句。 6. 配置Mybatis:创建一个配置类,添加@MapperScan注解指定Mapper接口所在的包路径。 7. 创建服务类:创建一个服务类,在其中注入Mybatis Mapper接口,并实现相应的业务逻辑。 8. 启动Eureka服务注册中心:如果使用了Eureka作为服务注册中心,需启动Eureka服务注册中心。在主类上添加@EnableEurekaClient注解。 9. 启动服务:运行Spring Boot项目,服务将自动注册到Eureka服务注册中心。 10. 调用服务:在需要调用服务的地方,使用@Autowired注解注入服务类,并调用相应的方法。 通过以上的步骤,我们就可以构建一个基于Spring CloudMybatis的框架,实现微服务的开发和数据库操作的封装。当然,在实际项目中,还需要根据具体需求进行进一步的配置和开发。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值