springboot of Three: springboot multi data source configuration + mybatis + mysql

springboot default configuration is greater than a single characteristic such that the configuration data is often convenient, but more than one data source arranged a little more complicated.

Source Address: https://github.com/jinjunzhu/spring-boot-mybatis.git

1. Integrated mybatis configure a single data source, only the following steps

1) connected to the configuration database

spring.datasource.url=jdbc:mysql://localhost:3306/zhujinjun?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=test
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

2) Configuration mybatis profile

3) write Mapper file

2. Integrated mybatis configure multiple data sources, need more configuration

1) configuration data source

######primary#############
datasource.first.jdbc-url=jdbc:mysql://localhost:3306/jinjunzhu?serverTimezone=UTC&characterEncoding=utf-8
datasource.first.username=root
datasource.first.password=123456
datasource.first.driver-class-name=com.mysql.cj.jdbc.Driver
  
  
######secondary#############  
datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/jinjunzhu1?serverTimezone=UTC&characterEncoding=utf-8
datasource.secondary.username=root
datasource.secondary.password=123456
datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver

2) configuration file mybatis

For the first data source

@Component("mybatisConfig")
@MapperScan(basePackages={"boot.repository.dao1"}, sqlSessionFactoryRef = "firstSqlSessionFactory")
public class MybatisConfig {

	@Bean(name="firstDataSource")
	@ConfigurationProperties(prefix="datasource.first")
	@Primary
	public DataSource firstDataSource() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "firstSqlSessionFactory")
	public SqlSessionFactory firstSqlSessionFactory(@Qualifier("firstDataSource") DataSource dataSource)
			throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		bean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis/mapper/mybatis-config.xml"));
		return bean.getObject();
	}

	@Bean(name = "firstTransactionManager")
	@Primary
	public DataSourceTransactionManager firstTransactionManager(@Qualifier("firstDataSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean(name = "firstSqlSessionTemplate")
	public SqlSessionTemplate firstSqlSessionTemplate(
			@Qualifier("firstSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
		return new SqlSessionTemplate(sqlSessionFactory);
	}

	//@Resource
	//@Qualifier("firstSqlSessionTemplate")
	//protected SqlSession firstSqlSession;
}

For the second data source

@Component("mybatisConfig1")
@MapperScan(basePackages={"boot.repository.dao2"}, sqlSessionFactoryRef = "secondSqlSessionFactory")
public class MybatisConfig1 {


    @Bean(name="secondDataSource")
    @ConfigurationProperties(prefix="datasource.secondary")
    public DataSource secondDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "secondSqlSessionFactory")
    public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDataSource") DataSource dataSource)
            throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis/mapper1/mybatis-config.xml"));
        return bean.getObject();
    }

    @Bean(name = "secondTransactionManager")
    public DataSourceTransactionManager secondTransactionManager(@Qualifier("secondDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "secondSqlSessionTemplate")
    public SqlSessionTemplate secondSqlSessionTemplate(
            @Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

3) to prepare and file dao class Mapper

From 2) seen in the image, different files and Mapper classes dao storage directory, the directory structure as follows:

3. Unit Testing

1) Test Data Source Code 1:

@Test
	public void testInsertEmployee(){
		Employee employee = employeeService.getEmployee("lisi");
		Assert.assertNull(employee);
		
		Employee employee1 = new Employee();
		employee1.setName("lisi");
		employee1.setDepartment("4");
		employee1.setNumber(2002950l);
		employeeService.insertEmployee(employee1);
		
		employee = employeeService.getEmployee("lisi");
		Assert.assertNotNull(employee);
		
	}

Start the test output class following log:

2) Test Data Source Code 2

@Transactional(value="secondTransactionManager", rollbackFor=Exception.class)
    public void testInsert() throws Exception{
        Assert.assertNull(departmentService.getDepartment("jinjunzhu"));

        Department department = new Department();
        department.setLevel(2);
        department.setName("jinjunzhu");
        department.setId(2l);
        departmentService.insertDepartment(department);

        Department department1 = departmentService.getDepartment("jinjunzhu");
        Assert.assertNotNull(department1);
    }

Perform the test method, the log follows:

From the above two testing methods, testing second data source needs to be on the test method plus transaction notes to support the rollback after the finish. Because of the increase in the data source mybatis @primary configuration class 1. Specific details of how to achieve, has not been studied.

4. The code has three classes controller supports http request for testing, as follows:

@Controller
@RequestMapping("/user")
public class UserController {


	
	@Resource
	private UserService userService;

	@RequestMapping("/{username}")
    @ResponseBody
    public String getPassword(@PathVariable String username) {
		String passwd = userService.getUser(username).getPassword();
		return passwd;
    }
	
	@RequestMapping("/saveUser/{username}")
    @ResponseBody
    public String saveUser(@PathVariable String username) {
		User user = new User();
		user.setUsername(username);
		user.setPassword("111111");
		try {
			userService.insert(user);
			return "success!";
		} catch (Exception e) {
			return "failure!";
		}
    }


}
@Controller
public class EmployeeController {

	@Resource
	private EmployeeService employeeService;
	
	@RequestMapping("/employee/{name}")
	@ResponseBody
	public String getEmployeebyName(@PathVariable String name){
		Employee employee = employeeService.getEmployee(name);
		return null == employee?null:employee.getDepartment();
	}
	
	@RequestMapping("/employee/save/{name}/{department}/{number}")
	@ResponseBody
	public String saveEmployeebyName(@PathVariable String name,@PathVariable String department,@PathVariable Long number){
		Employee employee = new Employee();
		employee.setName(name);
		employee.setDepartment(department);
		employee.setNumber(number);
		try{
			employeeService.insertEmployee(employee);
			return "success!";
		}catch(Exception e){
			return e.toString();
		}
	}

}
@Controller
public class DepartmentController {

	Logger logger = LoggerFactory.getLogger(getClass());

	@Resource
	private DepartmentService departmentService;
	
	@RequestMapping("/department/{name}")
	@ResponseBody
	public String getDepartment(@PathVariable String name){
		Department department = departmentService.getDepartment(name);
		return null == department?null:department.getName();
	}
	
	@RequestMapping("/department/save/{name}/{level}")
	@ResponseBody
	public void insertDepartment(@PathVariable String name,@PathVariable Integer level){
		Department department = new Department();
		department.setName(name);
		department.setLevel(level);
		try {
			departmentService.insertDepartment(department);
		} catch (Exception e) {
			logger.error("保存部门失败:", e);
		}
	}

}

 

After starting the project, the browser input

http://localhost:8080/employee/jinjunzhu,返回department

HTTP: // localhost: 8080 / the Employee / the Save / lisi / department3 / 3 , successfully saved

http://localhost:8080/department/department1,返回department1

http://localhost:8080/department/save/department3/3,保存成功

5. This project uses version:

springboot:2.1.6.RELEASE

org.mybatis:2.0.1

mysql-connector:8.0.16

6. configurations few notes:

1) @DependOn: such as the bean is initialized after the completion of the annotation initializes the current bean

2) @MapperScan: package the following notes in class as a mapper mybatis by the spring of unified management bean

3) @Primary: The default implementation preference

4) @Mapper: Specifies the interface class is mybatis mapper

Published 33 original articles · won praise 2 · views 40000 +

Guess you like

Origin blog.csdn.net/zjj2006/article/details/52213754