spring boot+gradle+mybatis多数据源配置

目录

  • 场景
  • 多数据源存在问题
  • demo演示流程
  • 代码结构
  • 引入jar包
  • 配置application.properties
  • 数据源初始化配置
  • mybatis生成对应的entity、mapper、和xml文件
  • 完成对应的service
  • 测试多数据源事务问题

1. 场景:

经常会碰到这种应用场景,比如说下订单的操作,有需要修改订单库中信息,又需要修改产品库中库存,这一个操作就是需要一次性操作两个数据源的情况。

2. 多数据源存在问题

事务问题

3. demo演示流程

  1. 引入jar包
  2. 配置application.properties
  3. 数据源初始化配置
  4. mybatis生成对应的entity、mapper、和xml文件
  5. 完成对应的service
  6. 测试多数据源事务问题

4. 代码结构

多数据源代码结构

5. 引入jar包(build.gradle)

spring boot版本使用2.0.6.RELEASE

implementation('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.2')
runtimeOnly('mysql:mysql-connector-java')
testImplementation('org.springframework.boot:spring-boot-starter-test')
compile 'tk.mybatis:mapper-spring-boot-starter:1.1.5'

6. 配置application.properties

first.datasource.jdbc-url=jdbc:mysql://ip:3306/test1?useSSL=false&useUnicode=true&characterEncoding=utf-8
first.datasource.username=root
first.datasource.password=**
first.datasource.driver-class-name=com.mysql.jdbc.Driver

second.datasource.jdbc-url=jdbc:mysql://ip:3306/test2?useSSL=false&useUnicode=true&characterEncoding=utf-8
second.datasource.username=root
second.datasource.password=***
second.datasource.driver-class-name=com.mysql.jdbc.Driver

7. 数据源初始化配置

  1. application取消默认数据源的初始化
  2. 数据源初始化
  3. 不同数据源对应不同的mapper

7.1 application取消默认数据源的初始化

SpringBootApplication 注解中后面添加exclude = {DataSourceAutoConfiguration.class})

@SpringBootApplication(exclude = {
		DataSourceAutoConfiguration.class
})
public class TwodatasourceApplication {

	public static void main(String[] args) {
		SpringApplication.run(TwodatasourceApplication.class, args);
	}
}

7.2 数据源初始化

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 javax.sql.DataSource;

/**
 * @program: twodatasource
 * @description: 数据源
 * @author: chengqj
 * @create: 2018-10-24 11:39
 **/
@Configuration
public class DataSourceConfig {

    @Bean(name = "ds1")
     // application.properteis中对应属性的前缀
    @ConfigurationProperties(prefix = "first.datasource")
    public DataSource dataSource1() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "ds2")
    // application.properteis中对应属性的前缀
    @ConfigurationProperties(prefix = "second.datasource") 
    public DataSource dataSource2() {
        return DataSourceBuilder.create().build();
    }
}

7.3 数据源初始化配置

数据源first

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.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * @program: twodatasource
 * @description: 数据库A配置
 * @author: chengqj
 * @create: 2018-10-24 11:40
 **/
@Configuration
//配置对应扫描的mapper路径
@MapperScan(basePackages = {"com.chengqj.twodatasource.dao.mapper"}, sqlSessionFactoryRef = "sqlSessionFactory1")
public class MybatisDbAConfig {

    @Autowired
    @Qualifier("ds1")
    private DataSource ds1;

    @Bean
    public SqlSessionFactory sqlSessionFactory1() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        // 使用first数据源, 连接first库
        factoryBean.setDataSource(ds1); 
        return factoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate1() throws Exception {
         // 使用上面配置的Factory
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory1()); 
        return template;
    }
}

数据源second

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.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * @program: twodatasource
 * @description: 数据源B
 * @author: chengqj
 * @create: 2018-10-24 11:42
 **/
@Configuration
@MapperScan(basePackages = {"com.chengqj.twodatasource.dao.mapper2"}, sqlSessionFactoryRef = "sqlSessionFactory2")
public class MybatisDbBConfig {
    @Autowired
    @Qualifier("ds2")
    private DataSource ds2;
    
    @Bean
    public SqlSessionFactory sqlSessionFactory2() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(ds2);
        return factoryBean.getObject();
    }
    
    @Bean
    public SqlSessionTemplate sqlSessionTemplate2() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory2());
        return template;
    }
}

8. mybatis生成对应的entity、mapper、和xml文件

entity TClass和Teacher
Teacher

import javax.persistence.*;

@Table(name = "t_teacher")
public class Teacher {
    /**
     * 班主任id
     */
    @Id
    private String id;

    /**
     * 姓名
     */
    private String name;

    /**
     * 获取班主任id
     *
     * @return id - 班主任id
     */
    public String getId() {
        return id;
    }

    /**
     * 设置班主任id
     *
     * @param id 班主任id
     */
    public void setId(String id) {
        this.id = id == null ? null : id.trim();
    }

    /**
     * 获取姓名
     *
     * @return name - 姓名
     */
    public String getName() {
        return name;
    }

    /**
     * 设置姓名
     *
     * @param name 姓名
     */
    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }
}

TClass

import javax.persistence.*;

@Table(name = "t_class")
public class TClass {
    /**
     * 班级表主键
     */
    @Id
    private String id;

    /**
     * 班级名称
     */
    private String name;

    /**
     * 获取班级表主键
     *
     * @return id - 班级表主键
     */
    public String getId() {
        return id;
    }

    /**
     * 设置班级表主键
     *
     * @param id 班级表主键
     */
    public void setId(String id) {
        this.id = id == null ? null : id.trim();
    }

    /**
     * 获取班级名称
     *
     * @return name - 班级名称
     */
    public String getName() {
        return name;
    }

    /**
     * 设置班级名称
     *
     * @param name 班级名称
     */
    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }
}

mapper
TClassMapper

import com.chengqj.twodatasource.dao.entity.TClass;
import tk.mybatis.mapper.common.Mapper;

public interface TClassMapper extends Mapper<TClass> {
}

TeacherMapper

import com.chengqj.twodatasource.dao.entity.Teacher;
import tk.mybatis.mapper.common.Mapper;

public interface TeacherMapper extends Mapper<Teacher> {
}

xml文件
TClassMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.chengqj.twodatasource.dao.mapper.TClassMapper">
  <resultMap id="BaseResultMap" type="com.chengqj.twodatasource.dao.entity.TClass">
    <!--
      WARNING - @mbg.generated
    -->
    <id column="id" jdbcType="VARCHAR" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
  </resultMap>
</mapper>

TeacherMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.chengqj.twodatasource.dao.mapper2.TeacherMapper">
  <resultMap id="BaseResultMap" type="com.chengqj.twodatasource.dao.entity.Teacher">
    <!--
      WARNING - @mbg.generated
    -->
    <id column="id" jdbcType="VARCHAR" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
  </resultMap>
</mapper>

9. 完成对应的service

TClassServiceImpl

import com.chengqj.twodatasource.dao.entity.TClass;
import com.chengqj.twodatasource.dao.mapper.TClassMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @program: twodatasource
 * @description: class服务类
 * @author: chengqj
 * @create: 2018-10-25 10:06
 **/
@Service
public class TClassServiceImpl {
    @Autowired
    private TClassMapper tclassMapper;

    public void save(TClass tclass){
        tclassMapper.insert(tclass);
    }
}

TeacherServiceImpl

import com.chengqj.twodatasource.dao.entity.Teacher;
import com.chengqj.twodatasource.dao.mapper2.TeacherMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @program: twodatasource
 * @description: teacher服务类
 * @author: chengqj
 * @create: 2018-10-25 10:08
 **/
@Service
public class TeacherServiceImpl {
    @Autowired
    private TeacherMapper teacherMapper;

    public void save(Teacher teacher) {
        teacherMapper.insert(teacher);
    }
}

10. 多数据源事务问题

JtaTestServiceImpl

import com.chengqj.twodatasource.dao.entity.TClass;
import com.chengqj.twodatasource.dao.entity.Teacher;
import com.chengqj.twodatasource.service.TClassServiceImpl;
import com.chengqj.twodatasource.service2.TeacherServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class JtaTestServiceImpl{

    @Autowired
    private TeacherServiceImpl teacherService;
    @Autowired
    private TClassServiceImpl tclassService;

    @Transactional( propagation = Propagation.REQUIRED, rollbackFor = { RuntimeException.class })
    public Map<String, Object> test01() {
        LinkedHashMap<String,Object> resultMap=new LinkedHashMap<String,Object>();
        TClass tClass=new TClass();
        tClass.setId("21");
        tClass.setName("8888");
        tclassService.save(tClass);

        Teacher teacher=new Teacher();
        teacher.setId("21");
        teacher.setName("8888");
        teacherService.save(teacher);
        //执行出错
        System.out.println(1/0);
        resultMap.put("state","success");
        resultMap.put("message","分布式事务问题");
        return resultMap;
    }
}

虽然service配置了异常回滚,但是因为是多数据库的情况,事务问题无法回滚,该问题可以使用atomikos框架进行解决。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot是一个基于Spring框架的快速开发框架,而Gradle是一种构建工具,用于管理项目的依赖和构建过程。MyBatis是一个数据访问框架,可用于将Java对象和数据库中的数据进行映射。 实现登录功能的步骤如下: 1. 首先,在Gradle的构建文件中添加MyBatis和相关的数据库驱动依赖。例如,在dependencies节点下添加如下代码: ```groovy implementation 'org.mybatis.spring.boot:mybatis-spring-boot-starter:2.2.0' implementation 'mysql:mysql-connector-java:8.0.26' ``` 2. 创建一个数据源配置类,用于配置数据库连接信息。在该类中,设置数据库的连接URL、用户名、密码等信息,并将该类注入到Spring容器中。例如: ```java @Configuration @MapperScan("com.example.mapper") // 指定MyBatis的Mapper接口所在的包路径 public class DataSourceConfig { @Value("${spring.datasource.url}") private String url; @Value("${spring.datasource.username}") private String username; @Value("${spring.datasource.password}") private String password; @Value("${spring.datasource.driver-class-name}") private String driverClassName; @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(driverClassName); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); return dataSource; } } ``` 3. 创建一个Mapper接口和对应的Mapper.xml文件,用于定义登录功能的SQL语句以及映射关系。例如,在Mapper接口中添加一个用于验证用户登录的方法: ```java public interface UserMapper { User findByUsernameAndPassword(@Param("username") String username, @Param("password") String password); } ``` 4. 编写Mapper.xml文件,将SQL语句和映射关系定义在该文件中。例如: ```xml <mapper namespace="com.example.mapper.UserMapper"> <select id="findByUsernameAndPassword" resultType="com.example.model.User"> SELECT * FROM user WHERE username = #{username} AND password = #{password} </select> </mapper> ``` 5. 创建一个Service类,用于实现登录的业务逻辑。在该类中,注入UserMapper接口,并编写登录逻辑。例如: ```java @Service public class UserService { @Autowired private UserMapper userMapper; public User login(String username, String password) { return userMapper.findByUsernameAndPassword(username, password); } } ``` 6. 创建一个Controller类,用于接收用户登录请求,并调用Service类中的登录方法进行验证。例如: ```java @RestController public class UserController { @Autowired private UserService userService; @PostMapping("/login") public User login(@RequestParam("username") String username, @RequestParam("password") String password) { return userService.login(username, password); } } ``` 综上所述,通过Spring BootGradle整合MyBatis,可以实现登录功能。通过创建数据源配置类、Mapper接口和对应的Mapper.xml文件,编写Service和Controller类,即可实现用户登录的验证功能。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值