springboot整合多数据源及事物

时间:2023-03-09 15:25:54
springboot整合多数据源及事物

  有两种方式:一种是分包的方式、一种是加注解的方式(@DataSource(ref=""))。

  分包方式:项目结构图如下:

                          springboot整合多数据源及事物

分为com.itmayiedu.test01、com.itmayiedu.test02两个包 里面是dao和service层,数据操作。

com.itmayiedu.datasource 里面放置数据源、数据库事物有关。两个配置相同。

两个数据源,需要在其中一个添加@Primary注解,作为主数据源,不然数据库找不到主的会报错;在springboot 2.0的版本后可以不需要添加@Primary注解

package com.itmayiedu.datasource;

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.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager; import javax.sql.DataSource; //DataSource01
@Configuration // 注册到springboot容器中
@MapperScan(basePackages = "com.itmayiedu.test01", sqlSessionFactoryRef = "test1SqlSessionFactory")
public class DataSource1Config { /**
*
* @methodDesc: 功能描述:(配置test1数据库)
* @author: 余胜军
* @param: @return
* @createTime:2017年9月17日 下午3:16:44
* @returnType:@return DataSource
* @copyright:上海每特教育科技有限公司
* @QQ:644064779
*/
@Bean(name = "test1DataSource")
@ConfigurationProperties(prefix = "spring.datasource.test1")
@Primary
public DataSource testDataSource() {
return DataSourceBuilder.create().build();
} /**
*
* @methodDesc: 功能描述:(test1 sql会话工厂)
* @author: 余胜军
* @param: @param
* dataSource
* @param: @return
* @param: @throws
* Exception
* @createTime:2017年9月17日 下午3:17:08
* @returnType:@param dataSource
* @returnType:@return
* @returnType:@throws Exception SqlSessionFactory
* @copyright:上海每特教育科技有限公司
* @QQ:644064779
*/
@Bean(name = "test1SqlSessionFactory")
@Primary
public SqlSessionFactory testSqlSessionFactory(@Qualifier("test1DataSource") DataSource dataSource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
// bean.setMapperLocations(
// new
// PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/test1/*.xml"));
return bean.getObject();
} /**
*
* @methodDesc: 功能描述:(test1 事物管理)
* @author: 余胜军
* @param: @param
* dataSource
* @param: @return
* @param: @throws
* Exception
* @createTime:2017年9月17日 下午3:17:08
* @returnType:@param dataSource
* @returnType:@return
* @returnType:@throws Exception SqlSessionFactory
* @copyright:上海每特教育科技有限公司
* @QQ:644064779
*/
@Bean(name = "test1TransactionManager")
@Primary
public DataSourceTransactionManager testTransactionManager(@Qualifier("test1DataSource") DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
} @Bean(name = "test1SqlSessionTemplate")
@Primary
public SqlSessionTemplate testSqlSessionTemplate(
@Qualifier("test1SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
return new SqlSessionTemplate(sqlSessionFactory);
} }

  application.properties:

###datasource1
spring.datasource.test1.driverClassName = com.mysql.jdbc.Driver
spring.datasource.test1.url = jdbc:mysql://localhost:3306/chapter3?useUnicode=true&characterEncoding=utf-8
spring.datasource.test1.username = root
spring.datasource.test1.password = zhaocheng
###datasource2
spring.datasource.test2.driverClassName = com.mysql.jdbc.Driver
spring.datasource.test2.url = jdbc:mysql://localhost:3306/chapter13?useUnicode=true&characterEncoding=utf-8
spring.datasource.test2.username = root
spring.datasource.test2.password = zhaocheng

  TestController:

  添加  @Transactional(transactionManager = "test1TransactionManager")   添加并且区别事物。

package com.itmayiedu.controller;

import com.itmayiedu.test01.service.UserServiceTest01;
import com.itmayiedu.test02.service.UserServiceTest02;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
@Slf4j
public class TestController { @Autowired
private UserServiceTest01 userServiceTest01;
@Autowired
private UserServiceTest02 userServiceTest02; @RequestMapping("/testString")
public String testString(){
log.info("testString");
return "springboot01 test";
} @RequestMapping("/insert")
@Transactional(transactionManager = "test1TransactionManager")
public Integer insertRole(String role_name,String note){
log.info("111111");
Integer a = userServiceTest01.insertRole(role_name, note);
int b = 100/Integer.valueOf(note);
return a;
} @RequestMapping("/update")
@Transactional(transactionManager = "test2TransactionManager")
public Integer updateRole(String role_name,String note){
log.info("222222");
Integer a = userServiceTest02.insertRole(role_name, note);
int b = 100/Integer.valueOf(note);
return a;
}
}

  启动类application:

package com.itmayiedu;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan; @SpringBootApplication
@ComponentScan
@MapperScan("com.itmayiedu.*.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}

这里面是添加    @MapperScan("com.itmayiedu.*.mapper")    在启动是扫包,或者也可以在 每个dao层添加@Mapper注解。

  UserMapperTest01:

package com.itmayiedu.test01.mapper;

import com.itmayiedu.entity.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository; @Repository
public interface UserMapperTest01 {
@Select("SELECT * FROM T_ROLE WHERE ROLE_NAME = #{role_name}")
User findByName(@Param("role_name") String role_name);
@Insert("INSERT INTO T_ROLE(ROLE_NAME, NOTE) VALUES(#{role_name}, #{note})")
int insert(@Param("role_name") String role_name, @Param("note") String note);
}

  UserServiceTest01:

package com.itmayiedu.test01.service;

import com.itmayiedu.test01.mapper.UserMapperTest01;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; @Service
public class UserServiceTest01 { @Autowired
private UserMapperTest01 userMapperTest01;
public Integer insertRole(String role_name,String note){
return userMapperTest01.insert(role_name, note);
}
}