目录
- 场景
- 多数据源存在问题
- demo演示流程
- 代码结构
- 引入jar包
- 配置application.properties
- 数据源初始化配置
- mybatis生成对应的entity、mapper、和xml文件
- 完成对应的service
- 测试多数据源事务问题
1. 场景:
经常会碰到这种应用场景,比如说下订单的操作,有需要修改订单库中信息,又需要修改产品库中库存,这一个操作就是需要一次性操作两个数据源的情况。
2. 多数据源存在问题
事务问题
3. demo演示流程
- 引入jar包
- 配置application.properties
- 数据源初始化配置
- mybatis生成对应的entity、mapper、和xml文件
- 完成对应的service
- 测试多数据源事务问题
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. 数据源初始化配置
- application取消默认数据源的初始化
- 数据源初始化
- 不同数据源对应不同的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框架进行解决。