In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what is the method of SpringBoot integrating MybatisPlus configuration multi-source enhanced plug-ins". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Project case introduction 1. Multi-data introduction
In actual projects, different databases are often used to meet the actual needs of the project. With the continuous increase of business concurrency, it is more and more common for a project to use multiple databases: master-slave replication, read-write separation, distributed database and so on.
2. Introduction to MybatisPlus
MyBatis-Plus (MP for short) is an enhancement tool of MyBatis, which is only enhanced but not changed on the basis of MyBatis, in order to simplify development and improve efficiency.
Plug-in features
No code intrusion: only enhancements are made and no changes are made, and the introduction of it will not affect existing projects. Powerful CRUD operation: through a small amount of configuration, you can achieve a single table, most CRUD operations to meet all kinds of use needs. Support for Lambda calls: through Lambda expressions, it is convenient to write all kinds of query conditions. Support for automatic generation of primary keys: freely configurable to solve primary key problems. Built-in code generation tool: code or Maven plug-in can be used to quickly generate each layer of code. Built-in paging plug-in: based on MyBatis physical paging, developers do not need to care about specific operations. Built-in performance analysis plug-in: can output Sql statements and their execution time. II. Multi-data source cases 1. Project structure
Note: the mapper layer and the mapper. XML layer are placed in different directories for the mybatis scan to load.
2 、 Multiple source configuration spring: # data source configuration datasource: type: com.alibaba.druid.pool.DruidDataSource admin-data: driverClassName: com.mysql.jdbc.Driver dbUrl: jdbc:mysql://127.0.0.1:3306/cloud-admin-data?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false username: root password: 123 initialSize: 20 maxActive: 100 minIdle: 20 maxWait: 60000 poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize : 30 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 30000 maxEvictableIdleTimeMillis: 60000 validationQuery: SELECT 1 FROM DUAL testOnBorrow: false testOnReturn: false testWhileIdle: true connectionProperties: druid.stat.mergeSql=true Druid.stat.slowSqlMillis=5000 filters: stat Wall user-data: driverClassName: com.mysql.jdbc.Driver dbUrl: jdbc:mysql://127.0.0.1:3306/cloud-user-data?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false username: root password: 123 initialSize: 20 maxActive: 100 minIdle: 20 maxWait: 60000 poolPreparedStatements: true maxPoolPreparedStatementPerConnectionSize: 30 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 30000 maxEvictableIdleTimeMillis: 60000 validationQuery: SELECT 1 FROM DUAL testOnBorrow: false TestOnReturn: false testWhileIdle: true connectionProperties: druid.stat.mergeSql=true Druid.stat.slowSqlMillis=5000 filters: stat,wall
Here, the parameters are in various forms, and you only need to configure parameter scanning.
3. Parameter scanning class @ Component@ConfigurationProperties (prefix = "spring.datasource.admin-data") public class DruidOneParam {private String dbUrl; private String username; private String password; private String driverClassName; private int initialSize; private int maxActive; private int minIdle; private int maxWait; private boolean poolPreparedStatements; private int maxPoolPreparedStatementPerConnectionSize; private int timeBetweenEvictionRunsMillis; private int minEvictableIdleTimeMillis; private int maxEvictableIdleTimeMillis; private String validationQuery; private boolean testWhileIdle; private boolean testOnBorrow; private boolean testOnReturn Private String filters; private String connectionProperties; / / omit GET and SET} 4, configure Druid connection pool @ Configuration@MapperScan (basePackages = {"com.data.source.mapper.one"}, sqlSessionTemplateRef = "sqlSessionTemplateOne") public class DruidOneConfig {private static final Logger LOGGER = LoggerFactory.getLogger (DruidOneConfig.class); @ Resource private DruidOneParam druidOneParam; @ Bean ("dataSourceOne") public DataSource dataSourceOne () {DruidDataSource datasource = new DruidDataSource () Datasource.setUrl (druidOneParam.getDbUrl ()); datasource.setUsername (druidOneParam.getUsername ()); datasource.setPassword (druidOneParam.getPassword ()); datasource.setDriverClassName (druidOneParam.getDriverClassName ()); datasource.setInitialSize (druidOneParam.getInitialSize ()); datasource.setMinIdle (druidOneParam.getMinIdle ()); datasource.setMaxActive (druidOneParam.getMaxActive ()); datasource.setMaxWait (druidOneParam.getMaxWait ()) Datasource.setTimeBetweenEvictionRunsMillis (druidOneParam.getTimeBetweenEvictionRunsMillis ()); datasource.setMinEvictableIdleTimeMillis (druidOneParam.getMinEvictableIdleTimeMillis ()); datasource.setMaxEvictableIdleTimeMillis (druidOneParam.getMaxEvictableIdleTimeMillis ()); datasource.setValidationQuery (druidOneParam.getValidationQuery ()); datasource.setTestWhileIdle (druidOneParam.isTestWhileIdle ()); datasource.setTestOnBorrow (druidOneParam.isTestOnBorrow ()); datasource.setTestOnReturn (druidOneParam.isTestOnReturn ()); datasource.setPoolPreparedStatements (druidOneParam.isPoolPreparedStatements ()) Datasource.setMaxPoolPreparedStatementPerConnectionSize (druidOneParam.getMaxPoolPreparedStatementPerConnectionSize ()); try {datasource.setFilters (druidOneParam.getFilters ());} catch (Exception e) {LOGGER.error ("druid configuration initialization filter", e);} datasource.setConnectionProperties (druidOneParam.getConnectionProperties ()); return datasource;} @ Bean public SqlSessionFactory sqlSessionFactoryOne throws Exception {SqlSessionFactoryBean factory = new SqlSessionFactoryBean () ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver (); factory.setDataSource (dataSourceOne ()); factory.setMapperLocations (resolver.getResources ("classpath*:/dataOneMapper/*.xml")); return factory.getObject ();} @ Bean (name= "transactionManagerOne") public DataSourceTransactionManager transactionManagerOne () {return new DataSourceTransactionManager (dataSourceOne ()) @ Bean (name = "sqlSessionTemplateOne") public SqlSessionTemplate sqlSessionTemplateOne () throws Exception {return new SqlSessionTemplate (sqlSessionFactoryOne ());}}
Matters needing attention
MapperScan is configured on the specified data source
SqlSessionFactory configuration scanned Mapper.xml address
DataSourceTransactionManager configures transactions for this data source
The configuration methods of the two data sources are the same, so I won't go into detail.
5. Operation case
Data source 1: simple query
@ Servicepublic class AdminUserServiceImpl implements AdminUserService {@ Resource private AdminUserMapper adminUserMapper; @ Override public AdminUser selectByPrimaryKey (Integer id) {return adminUserMapper.selectByPrimaryKey (id);}}
Data source 2: transaction operation
@ Servicepublic class UserBaseServiceImpl implements UserBaseService {@ Resource private UserBaseMapper userBaseMapper; @ Override public UserBase selectByPrimaryKey (Integer id) {return userBaseMapper.selectByPrimaryKey (id);} / / using the transaction of the specified data source @ Transactional (value = "transactionManagerTwo") @ Override public void insert (UserBase record) {/ / where the data write failed userBaseMapper.insert (record); / / int I = 1Comp0;}}
Note: here you need to specify the transaction manager for the data source configuration.
3. MybatisPlus case 1, core dependency com.baomidou mybatis-plus-boot-starter 3.0.7.1 com.baomidou mybatis-plus-generator com.baomidou mybatis-plus 3.0.7.12, Configuration file mybatis-plus: mapper-locations: classpath*:/mapper/*.xml typeAliasesPackage: com.digital.market.*.entity global-config: db-config: id-type: AUTO field-strategy: NOT_NULL logic-delete-value:-1 logic-not-delete-value: 0 banner: false configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl map-underscore-to-camel-case: true cache- Enabled: false call-setters-on-nulls: true jdbc-type-for-null: 'null'3, Layered configuration of mapper layer UserBaseMapper extends BaseMapper implementation layer UserBaseServiceImpl extends ServiceImpl implements UserBaseService interface layer UserBaseService extends IService4, mapper.xml file id User_name, pass_word, phone, email, create_time, update_time, state select * from hc_user_base
Matters needing attention
The methods in BaseMapper are implemented by default; you can also customize the implementation of some of your own methods.
5. Demo interface @ RestController@RequestMapping ("/ user") public class UserBaseController {private static final Logger LOGGER = LoggerFactory.getLogger (UserBaseController.class); @ Resource private UserBaseService userBaseService; @ RequestMapping ("/ info") public UserBase getUserBase () {return userBaseService.getById (1);} @ RequestMapping ("/ queryInfo") public String queryInfo () {UserBase userBase1 = userBaseService.getOne (new QueryWrapper (). OrderByDesc ("create_time")) LOGGER.info ("flashback value: {}", userBase1.getUserName ()); Integer count = userBaseService.count (); LOGGER.info ("Total query: {}", count); UserBase userBase2 = new UserBase (); userBase2.setId (1); userBase2.setUserName ("spring"); boolean resFlag = userBaseService.saveOrUpdate (userBase2) LOGGER.info ("Save updates: {}", resFlag); Map listByMap = new HashMap (); listByMap.put ("state", "0"); Collection listMap = userBaseService.listByMap (listByMap); LOGGER.info ("ListByMap query: {}", listMap); boolean removeFlag = userBaseService.removeById (3); LOGGER.info ("Delete data: {}", removeFlag) Return "success";} @ RequestMapping ("/ queryPage") public IPage queryPage () {QueryParam param = new QueryParam (); param.setPage (1); param.setPageSize (10); param.setUserName ("cicada"); param.setState (0); return userBaseService.queryPage (param) @ RequestMapping ("/ pageHelper") public PageInfo pageHelper () {return userBaseService.pageHelper (new QueryParam ());}}
Here the pageHelper method is customized using the PageHelper plug-in.
This is the end of the content of "how SpringBoot integrates MybatisPlus configuration multi-source enhancement plug-ins". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 261
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.