springboot使用mybatis连接两个mysql

介绍:一个项目里使用mybatis连接两个mysql

1.yml配置

  datasource:
    devicedb:
      jdbc-url: jdbc:mysql://127.0.0.1:3306/industry_device?serverTimezone=GMT%2B8
      username: root
      password: 123456
      driver-class-name: com.mysql.jdbc.Driver
    userdb:
      jdbc-url: jdbc:mysql://127.0.0.1:3306/industry_admin?serverTimezone=GMT%2B8
      username: root
      password: 123456
      driver-class-name: com.mysql.jdbc.Driver

移除:

  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.industry.project.entity      #所有Entity别名类所在包

2.配置config文件,一共需要两个config文件,分别配置两个不同的数据库

前提:准备好两个数据库的entity、service、mapper和dao文件

1、devicedb数据库配置文件:MyBatisConfig,这里我以devicedb数据库为主数据库,所以在配置上添加了@Primary标签。

package com.industry.project.config;



import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;


@Configuration
@EnableTransactionManagement //开启事务
@MapperScan(basePackages = "com.industry.project.dao",sqlSessionTemplateRef  = "devSqlSessionTemplate")
public class MyBatisConfig {

    @Bean(name = "devDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.devicedb")
    @Primary	//主数据库需要
    public DataSource testDataSource() {
        System.out.println("初始化devDataSource的数据源");
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "oldSqlSessionFactory")
    @Primary
    public SqlSessionFactory oldSqlSessionFactory(@Qualifier("devDataSource") DataSource dataSource) throws Exception {
        //SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        //配置自动填充时间
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setMetaObjectHandler(new MyMetaObjectHandlerConfig()); //注意:实现了MetaObjectHandler,为了实现数据创建时间自动添加
        bean.setGlobalConfig(globalConfig);
        bean.setDataSource(dataSource);
//        bean.setTypeEnumsPackage("com.cn.slt.exchange.enums");
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "devSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("oldSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }


    //引入分页插件
    @Bean
    public PaginationInterceptor paginationInterceptor2() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        // 设置请求的页面大于最大页后操作, true调回到首页,false 继续请求  默认false
        paginationInterceptor.setOverflow(true);
        // 设置最大单页限制数量,默认 500 条,-1 不受限制
        paginationInterceptor.setLimit(1000);
        return paginationInterceptor;
    }
}

2、userdb数据库配置文件:MyBatisConfig2

import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

@Configuration
@EnableTransactionManagement //开启事务
@MapperScan(basePackages = "com.industry.project.user.udao",sqlSessionTemplateRef  = "newsSqlSessionTemplate")
public class MyBatisConfig2 {

    @Bean(name = "newsDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.userdb")
    public DataSource testDataSource() {
        System.out.println("初始化新的数据源");
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "newsSqlSessionFactory")
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("newsDataSource") DataSource dataSource) throws Exception {
        //SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        //配置自动填充时间
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setMetaObjectHandler(new MyMetaObjectHandlerConfig());
        bean.setGlobalConfig(globalConfig);
        bean.setDataSource(dataSource);
//        bean.setTypeEnumsPackage("com.cn.slt.exchange.enums");  //多数据源配置了后必须在这里设置enums的指向包,在pom里面设置无效
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper2/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "newsTransactionManager")
    public DataSourceTransactionManager testTransactionManager(@Qualifier("newsDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "newsSqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("newsSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}

2.1、MyMetaObjectHandlerConfig文件代码(需要的拿走,也可以用自己的)。


import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MyMetaObjectHandlerConfig  implements MetaObjectHandler {

    /**
     * 插入时时间
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        //根据属性名称设置值
        this.setFieldValByName("createDate",new Date(),metaObject);
        this.setFieldValByName("updateDate",new Date(),metaObject);
        //this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐使用)
        //this.fillStrategy(metaObject, "createTime", LocalDateTime.now()); // 也可以使用(3.3.0 该方法有bug请升级到之后的版本如`3.3.1.8-SNAPSHOT`)
        /* 上面选其一使用,下面的已过时(注意 strictInsertFill 有多个方法,详细查看源码) */
        //this.setFieldValByName("operator", "Jerry", metaObject);
        //this.setInsertFieldValByName("operator", "Jerry", metaObject);
    }

    /**
     * 修改时添加时间
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {

        this.setFieldValByName("updateDate", new Date(), metaObject);
        //this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); // 起始版本 3.3.0(推荐使用)
        //this.fillStrategy(metaObject, "updateTime", LocalDateTime.now()); // 也可以使用(3.3.0 该方法有bug请升级到之后的版本如`3.3.1.8-SNAPSHOT`)
        /* 上面选其一使用,下面的已过时(注意 strictUpdateFill 有多个方法,详细查看源码) */
        //this.setFieldValByName("operator", "Tom", metaObject);
        //this.setUpdateFieldValByName("operator", "Tom", metaObject);
    }
}

3、截图参考:

在这里插入图片描述

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
1. 创建Spring Boot项目 在Spring Initializr中创建一个基于Maven的Spring Boot项目,勾选Web、MyBatisMySQL等相关依赖。 2. 配置数据库 在application.properties文件中添加MySQL数据库的连接信息。 spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver 其中,test为数据库名,root为用户名和密码。 3. 创建数据库表 在MySQL中创建user和log两张表,分别用于存储用户信息和日志信息。 CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `log` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(255) NOT NULL, `content` varchar(255) NOT NULL, `create_time` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; 4. 创建实体类和Mapper接口 创建User和Log实体类,用于映射数据库表中的数据。同时创建UserMapper和LogMapper接口,用于操作数据库。 5. 创建Service和Controller 创建UserService和LogService,实现用户的登录和注册以及日志的提交和查询等功能。创建UserController和LogController,处理用户请求,调用Service层的方法,返回相应的结果。 6. 创建前端页面 使用Layui框架,创建登录、注册、提交日志和查询日志的前端页面。其中,登录和注册页面使用Ajax技术实现异步请求,提交日志和查询日志页面使用表格展示数据。 以上就是实现用户登录注册和日志提交的Spring Boot+MyBatis+Layui+MySQL的基本流程。具体实现细节可参考相关文档和源码。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值