十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
本篇内容介绍了“SpringBoot整合MybatisPlus配置多数据源增强插件的方法是什么”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
创新互联建站-专业网站定制、快速模板网站建设、高性价比定结网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式定结网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖定结地区。费用合理售后完善,十载实体公司更值得信赖。
实际的项目中,经常会用到不同的数据库以满足项目的实际需求。随着业务的并发量的不断增加,一个项目使用多个数据库:主从复制、读写分离、分布式数据库等方式,越来越常见。
MyBatis-Plus(简称 MP)是一个MyBatis的增强工具,在MyBatis的基础上只做增强不做改变,为简化开发、提高效率而生。
插件特点
无代码侵入:只做增强不做改变,引入它不会对现有工程产生影响。 强大的 CRUD 操作:通过少量配置即可实现单表大部分 CRUD 操作满足各类使用需求。 支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件。 支持主键自动生成:可自由配置,解决主键问题。 内置代码生成工具:采用代码或者 Maven 插件可快速生成各层代码。 内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作。 内置性能分析插件:可输出 Sql 语句以及其执行时间。
注意:mapper层和mapper.xml层分别放在不同目录下,以便mybatis扫描加载。
spring: # 数据源配置 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
这里参数的形式是多样的,只需要配置参数扫描即可。
@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; // 省略 GET 和 SET }
@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()); } }
注意事项
MapperScan 在指定数据源上配置;
SqlSessionFactory 配置扫描的Mapper.xml地址 ;
DataSourceTransactionManager 配置该数据源的事务;
两个数据源的配置手法相同,不赘述 ;
数据源一:简单查询
@Service public class AdminUserServiceImpl implements AdminUserService { @Resource private AdminUserMapper adminUserMapper ; @Override public AdminUser selectByPrimaryKey (Integer id) { return adminUserMapper.selectByPrimaryKey(id) ; } }
数据源二:事务操作
@Service public class UserBaseServiceImpl implements UserBaseService { @Resource private UserBaseMapper userBaseMapper ; @Override public UserBase selectByPrimaryKey(Integer id) { return userBaseMapper.selectByPrimaryKey(id); } // 使用指定数据源的事务 @Transactional(value = "transactionManagerTwo") @Override public void insert(UserBase record) { // 这里数据写入失败 userBaseMapper.insert(record) ; // int i = 1/0 ; } }
注意:这里的需要指定该数据源配置的事务管理器。
com.baomidou mybatis-plus-boot-starter 3.0.7.1 com.baomidou mybatis-plus-generator com.baomidou mybatis-plus 3.0.7.1
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'
mapper层 UserBaseMapper extends BaseMapper实现层 UserBaseServiceImpl extends ServiceImpl implements UserBaseService 接口层 UserBaseService extends IService
id, user_name, pass_word, phone, email, create_time, update_time, state
注意事项
BaseMapper中的方法都已默认实现;这里也可以自定义实现一些自己的方法。
@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("倒叙取值:{}",userBase1.getUserName()); Integer count = userBaseService.count() ; LOGGER.info("查询总数:{}",count); UserBase userBase2 = new UserBase() ; userBase2.setId(1); userBase2.setUserName("spring"); boolean resFlag = userBaseService.saveOrUpdate(userBase2) ; LOGGER.info("保存更新:{}",resFlag); Map listByMap = new HashMap<>() ; listByMap.put("state","0") ; Collection listMap = userBaseService.listByMap(listByMap) ; LOGGER.info("ListByMap查询:{}",listMap); boolean removeFlag = userBaseService.removeById(3) ; LOGGER.info("删除数据:{}",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()) ; } }
这里pageHelper方法是使用PageHelper插件自定义的方法。
“SpringBoot整合MybatisPlus配置多数据源增强插件的方法是什么”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注创新互联网站,小编将为大家输出更多高质量的实用文章!