Spring boot integrates the implementation method of mybatis using multiple data sources
preface
This tutorial tends to be practical. The program ape directly adds the copy code to its own project and can be used after simple modification. However, springboot and mybatis are not introduced here. If readers want to know, they can leave me a message and pay continuous attention. I will update it slowly in the future. (for the code part in the black area, the Android phone can manually slide to the left to view all the codes)
integration
In fact, integration is very simple. If gradle is used, it is in build Add to gradle file
If you use maven, it's in POM XML file
Single library configuration:
After the introduction, by default, spring boot will automatically configure a datasource for us. It will search the jar package of H2, HSQLDB and other memory databases in the classpath. If it is found, it will automatically configure a datasource of the memory database.
If in application YML or application Spring. Is specified in property datasource.* Spring boot will use the configuration to create a datasource.
Then the sqlsessionfactorybean and sqlsessiontemplate using the datasource will be automatically created. It will automatically scan your mappers, connect to sqlsessiontemplate, and register in the spring context.
See datasourceproperties for more parameters
Multi library configuration:
Due to business needs, the project needs to use multiple databases for business development at the same time:
First, we must be in application Customize the configuration of two data sources in property. One uses first datasource.*, The other uses second datasource.*, In order to make others see what library is connected at a glance, you can use the database name, such as user library, you can use user datasource.*, When using multiple data sources, all necessary configurations cannot be omitted.
Directly to the code, my approach is to create two data sources with two configuration classes:
@Primary / / this annotation indicates which one is selected by default when there are multiple implementation classes that can be injected into the same interface, instead of allowing the autowire annotation to report an error. The official website requires that when there are multiple data sources, one data source must be specified and the other data source does not need to be added.
@Qualifier injects by name, usually in an instance with multiple types of the same (for example, an instance with multiple datasource types).
The user code structure is as follows:
summary
The above is the implementation method of spring boot integrating mybatis using multiple data sources introduced by Xiaobian. I hope it will be helpful to you. If you have any questions, please leave me a message and Xiaobian will reply to you in time. Thank you very much for your support for the programming tips website!