spring boot 配置MyBatis,支持多个数据源和分页插件
来源:互联网 发布:凯哥java 编辑:程序博客网 时间:2024/05/21 09:15
spring boot中的MyBatis配置是比较复杂的。
下面总结针对mySql数据库的配置和使用的详细过程(有两个数据库:名字为test和my_db):
1、引入依赖:
pom.xml文件中,添加:
<!-- Begin of DB related --><dependency> <!-- for ChainedTransactionManager configuration --><groupId>org.springframework.data</groupId><artifactId>spring-data-commons</artifactId></dependency><dependency> <!-- exclude掉缺省的jdbc配置 --><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId><exclusions><exclusion><groupId>org.apache.tomcat</groupId><artifactId>tomcat-jdbc</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.0</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.3.0</version></dependency><dependency> <!-- 连接池 --><groupId>com.zaxxer</groupId><artifactId>HikariCP</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency> <!-- mybatis 分页插件 --> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.1.6</version> </dependency><!-- End of DB related -->
2、开始配置:
2.1、在application.yml中定义mySql的ip和port,以方便以后使用不同的profile来区分不同的环境(development, test, production):
server: port: 8081mysql: ipPort: localhost:3306
/** * test库数据源 * 使用方法:在DAO层interface中使用这个注解 * */public @interface TestRepository {}
/** * my_db库数据源 * 使用方法:在DAO层interface中使用这个注解 * */public @interface MyDbRepository {}
/** * DataSource、SqlSessionFactory和Transaction Manager 配置 * @author XuJijun * */@Configuration@EnableTransactionManagementpublic class MyBatisConfig implements TransactionManagementConfigurer{private final static Logger logger = LoggerFactory.getLogger(MyBatisConfig.class);//数据库连接相关的参数:private String driverClassName = "com.mysql.jdbc.Driver";@Value("${mysql.ipPort}") private String jdbcIpPort; //从配置文件中获取private String jdbcUrl = "jdbc:mysql://%s/%s?useUnicode=true&characterEncoding=UTF-8";private String userName = "root";private String password = "123456";//连接池相关的参数://等待从连接池中获得连接的最大时长(毫秒),超过这个时长还没可用的连接则发生SQLException, 缺省:30秒private long connectionTimeout = 30000;//一个连接idle状态的最大时长(毫秒),超时则被释放(retired),缺省:10分钟private long idleTimeout = 600000;//一个连接的生命时长(毫秒),超时而且没被使用则被释放(retired),缺省:30分钟,建议设置比数据库超时时长少30秒以上,//参考MySQL wait_timeout参数(show variables like '%timeout%';)private long maxLifetime = 1765000;//连接池中允许的最大连接数。缺省值:10;推荐的公式:((core_count * 2) + effective_spindle_count)private int maximumPoolSize = 15;/** * 配置dataSource,使用Hikari连接池 */@Bean(destroyMethod = "close")@Primarypublic DataSource dataSource1(){HikariConfig config = new HikariConfig();config.setDriverClassName(driverClassName);config.setJdbcUrl(String.format(jdbcUrl, jdbcIpPort, "test"));config.setUsername(userName);config.setPassword(password);config.setConnectionTimeout(connectionTimeout); config.setIdleTimeout(idleTimeout);config.setMaxLifetime(maxLifetime);config.setMaximumPoolSize(maximumPoolSize);HikariDataSource ds = new HikariDataSource(config);return ds;}@Bean(destroyMethod = "close") public DataSource dataSource2(){HikariConfig config = new HikariConfig();config.setDriverClassName(driverClassName);config.setJdbcUrl(String.format(jdbcUrl, jdbcIpPort, "my_db"));config.setUsername(userName);config.setPassword(password);config.setConnectionTimeout(connectionTimeout);config.setIdleTimeout(idleTimeout);config.setMaxLifetime(maxLifetime);config.setMaximumPoolSize(maximumPoolSize);HikariDataSource ds = new HikariDataSource(config);return ds;}/** * 配置SqlSessionFactory: * - 创建SqlSessionFactoryBean,并指定一个dataSource; * - 设置这个分页插件:https://github.com/pagehelper/Mybatis-PageHelper; * - 指定mapper文件的路径; */@Bean public SqlSessionFactory sqlSessionFactory1() {SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource1()); //分页插件 PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); properties.setProperty("dialect", "mysql"); properties.setProperty("reasonable", "false"); properties.setProperty("pageSizeZero", "true"); pageHelper.setProperties(properties); bean.setPlugins(new Interceptor[]{pageHelper}); try { //指定mapper xml目录 ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));return bean.getObject();} catch (Exception e) {logger.error(e.getMessage(), e);throw new RuntimeException(e);}}@Bean public SqlSessionFactory sqlSessionFactory2() {SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource2()); //分页插件 PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); properties.setProperty("dialect", "mysql"); properties.setProperty("reasonable", "false"); properties.setProperty("pageSizeZero", "true"); pageHelper.setProperties(properties); bean.setPlugins(new Interceptor[]{pageHelper}); try { //指定mapper xml目录 ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));return bean.getObject();} catch (Exception e) {logger.error(e.getMessage(), e);throw new RuntimeException(e);}}/** * Transaction 相关配置 * 因为有两个数据源,所有使用ChainedTransactionManager把两个DataSourceTransactionManager包括在一起。 */@Overridepublic PlatformTransactionManager annotationDrivenTransactionManager() {DataSourceTransactionManager dtm1 = new DataSourceTransactionManager(dataSource1());DataSourceTransactionManager dtm2 = new DataSourceTransactionManager(dataSource2());ChainedTransactionManager ctm = new ChainedTransactionManager(dtm1, dtm2);return ctm;}}
2.4、配置MyBatis Mapper Scanner:
/** * 配置MyBatis Mapper Scanner * @author XuJijun * */@Configuration@AutoConfigureAfter(MyBatisConfig.class)public class MyBatisMapperScannerConfig {/** * - 设置SqlSessionFactory; * - 设置dao所在的package路径; * - 关联注解在dao类上的Annotation名字; */@Beanpublic MapperScannerConfigurer mapperScannerConfigurer1() {MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory1");mapperScannerConfigurer.setBasePackage("com.xjj.dao");mapperScannerConfigurer.setAnnotationClass(TestRepository.class);return mapperScannerConfigurer;}@Beanpublic MapperScannerConfigurer mapperScannerConfigurer2() {MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory2");mapperScannerConfigurer.setBasePackage("com.xjj.dao");mapperScannerConfigurer.setAnnotationClass(MyDbRepository.class);return mapperScannerConfigurer;}}
3、使用
3.1、定义一个实体类Person(略):
3.2、定义Dao:
3.3、定义mapper(如有需要):
4、测试:
4.1、单元测试代码:
4.1、测试结果:
结果表明:已经配置成功,并可以正常使用。
源代码:https://github.com/xujijun/my-spring-boot
1 0
- spring boot 配置MyBatis,支持多个数据源和分页插件
- spring boot和mybatis集成分页插件
- spring + mybatis配置多个数据源
- Spring Boot + Mybatis多数据源和动态数据源配置
- Spring Boot + Mybatis多数据源和动态数据源配置
- spring boot mybatis+分页配置
- Spring Boot : 集成mybatis、pagehelper插件、开启事务、druid数据源配置、mybatis-generator(十一)
- Spring Boot+Mybatis动态数据源配置
- MyBatis+Spring分页插件配置
- Spring Boot集成MyBatis与分页插件
- Spring Boot集成MyBatis与分页插件
- spring boot mybatis分页插件的使用
- Mybatis-分页插件(spring boot下)
- spring mvc + mybatis配置多个数据源问题。
- MyBatis配置多个数据源
- Spring-Boot项目+Spring-Mybatis+分页插件+Spring单元测试整合
- spring boot 配置单数据源和多controller问题
- spring 4.0.6 + mybatis 3.2.5 + mybatis-spring 1.2.3 构造多个数据源的配置
- 面向对象之instanceof
- Java中的this关键字
- iOS Label文本自适应高度
- Android 6.0 运行时权限处理完全解析
- webAPP常用控件之——swiper
- spring boot 配置MyBatis,支持多个数据源和分页插件
- 数组的初始化之---静态初始化和动态初始化
- 最牛逼android上的图表库MpChart(三) 条形图
- JS 禁用移动流量球、禁用iframe嵌入
- iOS毛玻璃效果的实现(针对iOS8以上SDK)
- 2042不容易系列之二(从后往前递推)
- Universal-Image-Loader(Android开源项目)
- SQL学习总结(1)
- Java泛型详解