The original address: https://blog.lanweihong.com/p…
Making: spring – the boot – mybatis – multiple – data – source
Add related dependency packages
Edit the pom.xml file to add the relevant dependencies:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.8</version> <relativePath/> </parent> <properties> <mysql.driver.version>8.0.16</mysql.driver.version> < mybatis. Spring. The boot. Version > 1.3.2 < / mybatis. Spring. The boot. Version > < druid. Version > 1.1.10 < / druid version > < tk. Mybatis. Version > 2.1.5 < / tk. Mybatis. Version > < lombok. Version > 1.16.18 < / lombok version > < / properties > < dependencies > <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis.spring.boot.version}</version> </dependency> <! -- mysql driver --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.driver.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>${druid.version}</version> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>${tk.mybatis.version}</version> </dependency> </dependencies>
configurationapplication.yml
file
Configure the data source in the configuration file Application.yml:
spring: datasource: type: com.alibaba.druid.pool.DruidDataSource username: root password: Aa123456. druid: driver-class-name: com.mysql.cj.jdbc.Driver initial-size: 5 max-active: 50 max-wait: 60000 min-idle: Book 5 # configuration data sources, customizable book: # type: com. Alibaba. Druid. Pool. # DruidDataSource driver - class - name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/db01? useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=Asia/Shanghai # Username: root password: # 1 # configuration user data source user: url: JDBC: mysql: / / localhost: 3306 / db02? useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=Asia/Shanghai # Username: root password: 1
Manually configure the data source
Master data source configuration
Create the configuration class BookDataSourceConfig, Configuration class to a DataSource, DataSourceTransactionManager, SqlSessionFactory, SqlSessionTemplate four data items are configured. When multiple data sources exist in the system, one of them must be the Primary data source, embellished with the @primary annotation.
BookDataSourceConfig configuration class:
@Configuration // Automatically switch data sources by configurable 'BasepackAges' and' SqlSessionTemplateRef 'in the' @MapPersCan 'annotation @MapPersCan (BasepackAges = "com.lanweihong.dao.book", sqlSessionFactoryRef = "bookSqlSessionFactory", sqlSessionTemplateRef = "bookSqlSessionTemplate") public class BookDataSourceConfig { public static final String MAPPER_LOCATION = "classpath:mapper/book/*.xml"; /** * @primary If there are more than one Bean of the same class, this Bean is preferred. If there are multiple data sources, one Primary data source must be configured. With the comments marked * @ return * / @ Primary @ Bean (" bookDataSource ") @ ConfigurationProperties (" spring. The datasource. The druid. Book ") to the public DataSource bookDataSource(){ return DruidDataSourceBuilder.create().build(); } @Primary @Bean("bookTransactionManager") public DataSourceTransactionManager bookTransactionManager() { return new DataSourceTransactionManager(bookDataSource()); } @Primary @Bean("bookSqlSessionFactory") public SqlSessionFactory sqlSessionFactory(@Qualifier("bookDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource); sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION)); return sqlSessionFactoryBean.getObject(); } @Primary @Bean("bookSqlSessionTemplate") public SqlSessionTemplate sqlSessionTemplate(@Qualifier("bookDataSource") DataSource dataSource) throws Exception { return new SqlSessionTemplate(sqlSessionFactory(dataSource)); }}
MyBatis automatically switches data sources by using the ScanPacket configuration and the corresponding SqlSessionTemplate, that is, by configurable BasePackages and SqlSessionTemplate in the @MapPersCan annotation:
@MapperScan(basePackages = "com.lanweihong.dao.book",
sqlSessionFactoryRef = "bookSqlSessionFactory", sqlSessionTemplateRef = "bookSqlSessionTemplate")
Configuring a second data source
Write the configuration class UserDataSourceConfig:
@Configuration @MapperScan(basePackages = "com.lanweihong.dao.user", sqlSessionTemplateRef = "userSqlSessionTemplate") public class UserDataSourceConfig { public static final String MAPPER_LOCATION = "classpath:mapper/user/*.xml"; / user data * * * * @ return * / @ Bean (" userDataSource ") @ ConfigurationProperties (" spring. The datasource. The druid. User ") of the public DataSource userDataSource(){ return DruidDataSourceBuilder.create().build(); } @Bean("userTransactionManager") public DataSourceTransactionManager userTransactionManager() { return new DataSourceTransactionManager(userDataSource()); } @Bean("userSqlSessionFactory") public SqlSessionFactory userSqlSessionFactory(@Qualifier("userDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource); sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION)); return sqlSessionFactoryBean.getObject(); } @Bean("userSqlSessionTemplate") public SqlSessionTemplate userSqlSessionTemplate(@Qualifier("userDataSource") DataSource dataSource) throws Exception { return new SqlSessionTemplate(userSqlSessionFactory(dataSource)); }}
At this point, the configuration of the different data sources is complete and you are ready to use it.
use
Write and use DAO and Service as normal as usual. Spring will automatically switch the corresponding data source according to the mapping of data source configuration. There is no need to specify the data source in the Service, just use it directly.
The followingDAO/Mapper/Service/Controller
The code is a sample code, only part of the code listed, complete code please see:https://github.com/lanweihong…
IBookDao:
public interface IBookDao extends BaseMapper<BookDO> {
BookDO getByBookName(@Param("bookName") String bookName);
}
BookMapper. XML:
<? The 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.lanweihong.dao.book.IBookDao"> <resultMap id="BaseResultMap" type="com.lanweihong.entity.BookDO"> <id column="id" jdbcType="BIGINT" property="id" /> <result column="version" jdbcType="INTEGER" property="version" /> <result column="book_name" jdbcType="VARCHAR" property="bookName" /> <result column="status" jdbcType="TINYINT" property="status" /> <result column="add_time" jdbcType="TIMESTAMP" property="addTime" /> </resultMap> <sql id="BaseColumnList"> id, version, book_name, status, add_time </sql> <select id="getByBookName" resultMap="BaseResultMap"> SELECT <include refid="BaseColumnList" /> FROM book WHERE book_name = #{bookName} </select> </mapper>
Service:
@Service("bookService") public class BookServiceImpl implements IBookService { private final IBookDao bookDao; @Autowired public BookServiceImpl(IBookDao bookDao) { this.bookDao = bookDao; } @Override public List<BookDO> listAll() { return bookDao.selectAll(); } @Override public BookDO getByBookName(String bookName) { return bookDao.getByBookName(bookName); }}
Controller:
@RestController @RequestMapping("/api/v1/") public class MainController { private final IUserService userService; private final IBookService bookService; @Autowired public MainController(IUserService userService, IBookService bookService) { this.userService = userService; this.bookService = bookService; } @GetMapping("/books") public Map<String, Object> queryBooks(@RequestParam(value = "name", required = false) String bookName) { List<BookDO> books = new ArrayList<>(); if (StringUtil.isEmpty(bookName)) { books = this.bookService.listAll(); } else { BookDO book = bookService.getByBookName(bookName); books.add(book); } Map<String, Object> result = new HashMap<>(1); result.put("data", books); return result; } @GetMapping("/users") public Map<String, Object> queryUsers(@RequestParam(value = "name", required = false) String userName) { List<UserDO> users = new ArrayList<>(); if (StringUtil.isEmpty(userName)) { users = this.userService.listAll(); } else { UserDO user = userService.getByUserName(userName); users.add(user); } Map<String, Object> result = new HashMap<>(1); result.put("data", users); return result; }}
test
Start the application, in the browser to access http://127.0.0.1:8015/api/v1/users and http://127.0.0.1:8015/api/v1/books test;
The project structure
The project structure is as follows:
The code has been uploaded to Github: spring-boot-mybatis multiple-data-source
Reference documentation
- https://blog.csdn.net/acquain…