当前位置:   article > 正文

Springboot+Mybatis配置多数据源使用PageHelper分页_springboot mssql分页

springboot mssql分页

前言

公司项目由老的.net项目,迁移为现在的springcloud。迁移是个比较漫长的过程,导致公司现有数据源SqlServer和Mybatis两种。相对于单数据源,PageHelper分页插件,几乎不用而配置即可使用,而双数据源切换会导致语法报错。

PageHelper分页插件需要设定一个默认的数据库源,而SqlServer、mysql的部分语法不同。例如先用mysql查询时,分页插件默认使用mysql语句,切换sqlserver后,却依然使用mysql语法,导致查询失败。

例如,查询前一百条狗狗的姓名:

mysql:       SELECT name FROM tbl_dog LIMIT100;

sqlserver:  SELECT TOP 100 name FROM tbl_dog; 

解决思路:

   先配置多数据源,再配置多个SqlSessionFactory指定不同包路径下的mapper使用不同的数据源,此时不同的dao层就可以访问不同数据源。

一.配置数据源

    所用到的技术:springboot、mybatis、druid、mysql、sqlserver

确保自己两个不同的数据库,本文以mysql和sqlserver为例(其他数据源原理相同)

❶ pom.xml中导入相关依赖插件

  1. <!--分页插件-->
  2. <dependency>
  3. <groupId>com.github.pagehelper</groupId>
  4. <artifactId>pagehelper-spring-boot-starter</artifactId>
  5. <version>1.2.5</version>
  6. </dependency>
  7. <!--mybatis-->
  8. <dependency>
  9. <groupId>org.mybatis.spring.boot</groupId>
  10. <artifactId>mybatis-spring-boot-starter</artifactId>
  11. <version>1.3.2</version>
  12. </dependency>
  13. <!--druid-->
  14. <dependency>
  15. <groupId>com.alibaba</groupId>
  16. <artifactId>druid-spring-boot-starter</artifactId>
  17. <version>1.1.9</version>
  18. </dependency>
  19. <!--mysql连接驱动-->
  20. <dependency>
  21. <groupId>mysql</groupId>
  22. <artifactId>mysql-connector-java</artifactId>
  23. <version>5.1.39</version>
  24. <scope>runtime</scope>
  25. </dependency>
  26. <!--sql-server连接驱动-->
  27. <dependency>
  28. <groupId>com.microsoft.sqlserver</groupId>
  29. <artifactId>sqljdbc4</artifactId>
  30. <version>4.0</version>
  31. </dependency>

❷ 配置application.yml

  1. server:
  2. port: 8079
  3. tomcat:
  4. uri-encoding: UTF-8
  5. spring:
  6. datasource:
  7. type: com.alibaba.druid.pool.DruidDataSource
  8. dmysql:
  9. type: com.alibaba.druid.pool.DruidDataSource
  10. driverClassName: com.mysql.jdbc.Driver
  11. jdbcUrl: jdbc:mysql://(你的ip地址):3306/vipdb?useUnicode=true&characterEncoding=UTF-8&useSSL=true
  12. username: root
  13. password: root
  14. dsqlserver:
  15. type: com.alibaba.druid.pool.DruidDataSource
  16. driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
  17. jdbcUrl: jdbc:sqlserver://(你的ip地址):49508;Databasename=VIPDB
  18. username: root
  19. password: root

❸配置mysql,sqlsever

MySqlDataSourceConfig.java 文件(mysql)

  1. @Configuration
  2. @MapperScan(basePackages={"com.example.demo.mapper.*"}, sqlSessionFactoryRef="mysqlSessionFactory")
  3. public class MySqlDataSourceConfig {
  4. @Value("${spring.datasource.dmysql.type")
  5. private String type;
  6. @Value("${spring.datasource.dmysql.driverClassName}")
  7. private String driverClass;
  8. @Value("${spring.datasource.dmysql.jdbcUrl}")
  9. private String url;
  10. @Value("${spring.datasource.dmysql.username}")
  11. private String username;
  12. @Value("${spring.datasource.dmysql.password}")
  13. private String password;
  14. /**
  15. * 配置数据源基本信息
  16. */
  17. @Primary
  18. @Bean(value = "mysqlDataSource")
  19. public DataSource dataSource() {
  20. DruidDataSource datasource = new DruidDataSource();
  21. datasource.setDbType(type);
  22. datasource.setDriverClassName(driverClass);
  23. datasource.setUrl(url);
  24. datasource.setUsername(username);
  25. datasource.setPassword(password);
  26. return datasource;
  27. }
  28. @Bean(name = "mysqlTransactionManager")
  29. @Primary
  30. public DataSourceTransactionManager masterTransactionManager() {
  31. return new DataSourceTransactionManager(dataSource());
  32. }
  33. @Primary
  34. @Bean(name = "mysqlSessionFactory")
  35. public SqlSessionFactory mysqlSessionFactory(@Qualifier("mysqlDataSource") DataSource dataSource)
  36. throws Exception {
  37. final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
  38. //分页插件
  39. Interceptor interceptor = new PageInterceptor();
  40. Properties properties = new Properties();
  41. //数据库
  42. properties.setProperty("helperDialect", "mysql");
  43. //是否分页合理化
  44. properties.setProperty("reasonable", "false");
  45. interceptor.setProperties(properties);
  46. sessionFactory.setPlugins(new Interceptor[] {interceptor});
  47. sessionFactory.setDataSource(dataSource);
  48. return sessionFactory.getObject();
  49. }
  50. @Bean(name = "mysqlSessionTemplate")
  51. @Primary
  52. public SqlSessionTemplate mysqlSessionTemplate(@Qualifier("mysqlSessionFactory") SqlSessionFactory sqlSessionFactory){
  53. return new SqlSessionTemplate(sqlSessionFactory);
  54. }
  55. }

SqlServerDataSourceeConfig.java 文件 (sqlserver)

  1. @Configuration
  2. @MapperScan(basePackages = {"com.example.demo.mssql.mapper.*"}, sqlSessionFactoryRef = "mssqlSessionFactory")
  3. public class SqlServerDataSourceeConfig {
  4. @Value("${spring.datasource.dsqlserver.type}")
  5. private String type;
  6. @Value("${spring.datasource.dsqlserver.driverClassName}")
  7. private String driverClass;
  8. @Value("${spring.datasource.dsqlserver.jdbcUrl}")
  9. private String url;
  10. @Value("${spring.datasource.dsqlserver.username}")
  11. private String username;
  12. @Value("${spring.datasource.dsqlserver.password}")
  13. private String password;
  14. @Bean(value = "mssqlDataSource")
  15. public DataSource dataSource(){
  16. DruidDataSource datasource = new DruidDataSource();
  17. datasource.setDbType(type);
  18. datasource.setDriverClassName(driverClass);
  19. datasource.setUrl(url);
  20. datasource.setUsername(username);
  21. datasource.setPassword(password);
  22. return datasource;
  23. }
  24. @Bean(name = "mssqlTransactionManager")
  25. public DataSourceTransactionManager masterTransactionManager() {
  26. return new DataSourceTransactionManager(dataSource());
  27. }
  28. @Bean(name = "mssqlSessionFactory")
  29. public SqlSessionFactory mssqlSessionFactory(@Qualifier("mssqlDataSource") DataSource dataSource)
  30. throws Exception {
  31. final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
  32. //分页插件
  33. Interceptor interceptor = new PageInterceptor();
  34. Properties properties = new Properties();
  35. //数据库
  36. properties.setProperty("helperDialect", "sqlserver2012");
  37. //是否分页合理化
  38. properties.setProperty("reasonable", "false");
  39. interceptor.setProperties(properties);
  40. sessionFactory.setPlugins(new Interceptor[] {interceptor});
  41. sessionFactory.setDataSource(dataSource);
  42. return sessionFactory.getObject();
  43. }
  44. @Bean(name = "mssqlSessionTemplate")
  45. public SqlSessionTemplate mssqlSessionTemplate(@Qualifier("mssqlSessionFactory") SqlSessionFactory sqlSessionFactory){
  46. return new SqlSessionTemplate(sqlSessionFactory);
  47. }
  48. }

请确保@MapperScan中的basePackages 指定的mapper路径和本地一致

❹ 分页查询(以mysql为例)

  1. //controller
  2. @RestController
  3. public class VipController {
  4. @Autowired
  5. private VipService vipService;
  6. @GetMapping("/vip/name")
  7. public Object hello() {
  8. List<String> list = vipService.findVipNameAll();
  9. return list;
  10. }
  11. }
  12. //service层
  13. @Service
  14. public class VipService {
  15. @Autowired
  16. private VipMapper vipMapper;
  17. public List<String> findVipNameAll() {
  18. //查询第一页,每页3条数据,根据id升序
  19. PageInfo<String> pageInfo = PageHelper.startPage(1, 3,"id asc").doSelectPageInfo(()
  20. -> vipMapper.getVipNameAll());
  21. return pageInfo.getList();
  22. }
  23. }
  24. //dao层/mapper(我用注解简化此步骤)
  25. @Mapper
  26. public interface VipMapper {
  27. @Select("SELECT name from ap_vip")
  28. List<String> getVipNameAll();
  29. }

["VIP1","VIP2", "VIP3"]

这样就可以实现pagehelper针对不同包路径下的sql,进行不同的sql处理。

❻ Application启动类

  1. 首先要将springboot自带的DataSourceAutoConfiguration禁掉,因为它会读取application.properties文件的spring.datasource.* 属性并自动配置单数据源。在@SpringBootApplication注解中添加exclude属性排除。
  2. 因为系统启动的时候PageHelperAutoConfiguration会自动注册,在@SpringBootApplication注解中添加exclude属性排除自动配置。

项目地址:https://github.com/PureLeaves/springboot_datasource 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/你好赵伟/article/detail/88175
推荐阅读
相关标签
  

闽ICP备14008679号