這篇文章主要介紹,經過Spring Boot整合Mybatis後如何實如今一個工程中實現多數據源。同時可實現讀寫分離。css
環境:html
windows jdk 8 maven 3.0 IDEA
在mysql
中建立student
庫並執行下面查詢建立student
表java
-- ---------------------------- -- Table structure for student -- ---------------------------- DROP TABLE IF EXISTS `student`; CREATE TABLE `student` ( `sno` int(15) NOT NULL, `sname` varchar(50) DEFAULT NULL, `sex` char(2) DEFAULT NULL, `dept` varchar(25) DEFAULT NULL, `birth` date DEFAULT NULL, `age` int(3) DEFAULT NULL, PRIMARY KEY (`sno`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of student -- ---------------------------- INSERT INTO `student` VALUES ('1', '李同窗', '1', '王同窗學習成績很不錯', '2010-07-22', '17');
在mysql
中建立teacher
庫並執行下面查詢建立teacher
表mysql
-- ---------------------------- -- Table structure for teacher -- ---------------------------- DROP TABLE IF EXISTS `teacher`; CREATE TABLE `teacher` ( `Tno` varchar(20) NOT NULL DEFAULT '', `Tname` varchar(50) DEFAULT NULL, `sex` char(2) DEFAULT NULL, `dept` varchar(25) DEFAULT NULL, `birth` date DEFAULT NULL, `age` int(3) DEFAULT NULL, PRIMARY KEY (`Tno`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of teacher -- ---------------------------- INSERT INTO `teacher` VALUES ('1', '王老師', '1', '王老師上課很認真', '2018-07-06', '35');
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>cn.zhangbox</groupId> <artifactId>spring-boot-study</artifactId> <version>1.0-SNAPSHOT</version> </parent> <groupId>cn.zhangbox</groupId> <artifactId>spring-boot-mybatis-datasource</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>spring-boot-mybatis-datasource</name> <description>this project for Spring Boot</description> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <!-- 版本控制 --> <commons-lang3.version>3.4</commons-lang3.version> <commons-codec.version>1.10</commons-codec.version> <mybatis-spring-boot.version>1.2.0</mybatis-spring-boot.version> <lombok.version>1.16.14</lombok.version> <fastjson.version>1.2.41</fastjson.version> <druid.version>1.1.2</druid.version> </properties> <repositories> <!-- 阿里私服 --> <repository> <id>aliyunmaven</id> <url>http://maven.aliyun.com/nexus/content/groups/public/</url> </repository> </repositories> <dependencies> <!-- mybatis核心包 start --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis-spring-boot.version}</version> </dependency> <!-- mybatis核心包 end --> <!-- SpringWEB核心包 start --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- SpringWEB核心包 end --> <!-- mysql驅動核心包 start --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- mysql驅動核心包 end --> <!-- sprigTest核心包 start --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- sprigTest核心包 end --> <!-- commons工具核心包 start --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>${commons-lang3.version}</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>${commons-codec.version}</version> </dependency> <!-- commons工具核心包 end --> <!-- fastjson核心包 start --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>${fastjson.version}</version> </dependency> <!-- fastjson核心包 end --> <!-- druid核心包 start --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>${druid.version}</version> </dependency> <!-- druid核心包 end --> <!-- lombok核心包 start --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>${lombok.version}</version> </dependency> <!-- lombok核心包 end --> </dependencies> <build> <finalName>spring-boot-mybatis-datasource</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.19.1</version> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>springloaded</artifactId> <version>1.2.4.RELEASE</version> </dependency> </dependencies> <configuration> <mainClass>cn.zhangbox.admin.SpringBootDruidApplication</mainClass> <jvmArguments>-Dfile.encoding=UTF-8 -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 </jvmArguments> <executable>true</executable> <fork>true</fork> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <mainClass>cn.zhangbox.admin.SpringBootDruidApplication</mainClass> <jvmArguments>-Dfile.encoding=UTF-8 -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005</jvmArguments> <executable>true</executable> <fork>true</fork> </configuration> </plugin> </plugins> </build> </project>
注意:這裏引入了lombok
插件節省編寫實體類時候寫get
和set
方法,這裏在idea
中進行set
和get
操做須要下載lombok
插件,在設置頁面的plugins
中搜索lombok
插件在中央插件庫下載後重啓idea
便可,更詳細的lombok使用教程能夠查考:git
#公共配置 server: port: 80 tomcat: uri-encoding: UTF-8 spring: #激活哪個環境的配置文件 profiles: active: dev #鏈接池配置 datasource: #配置student庫驅動和鏈接池 student: driver-class-name: com.mysql.jdbc.Driver # 使用druid數據源 type: com.alibaba.druid.pool.DruidDataSource #配置teacher庫驅動和鏈接池 teacher: driver-class-name: com.mysql.jdbc.Driver # 使用druid數據源 type: com.alibaba.druid.pool.DruidDataSource druid: # 配置測試查詢語句 validationQuery: SELECT 1 FROM DUAL # 初始化大小,最小,最大 initialSize: 10 minIdle: 10 maxActive: 200 # 配置一個鏈接在池中最小生存的時間,單位是毫秒 minEvictableIdleTimeMillis: 180000 testOnBorrow: false testWhileIdle: true removeAbandoned: true removeAbandonedTimeout: 1800 logAbandoned: true # 打開PSCache,而且指定每一個鏈接上PSCache的大小 poolPreparedStatements: true maxOpenPreparedStatements: 100 # 配置監控統計攔截的filters,去掉後監控界面sql沒法統計,'wall'用於防火牆 filters: stat,wall,log4j # 經過connectProperties屬性來打開mergeSql功能;慢SQL記錄 connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 #mybatis mybatis: # 實體類掃描 type-aliases-package: cn.zhangbox.springboot.entity # 配置映射文件位置 mapper-locations: classpath:mapper/*.xml # 開啓駝峯匹配 mapUnderscoreToCamelCase: true --- #開發環境配置 server: #端口 port: 8080 spring: profiles: dev # 數據源配置 datasource: student: url: jdbc:mysql://127.0.0.1:3306/student?useUnicode=true&characterEncoding=utf8&useSSL=false&tinyInt1isBit=true username: root password: 123456 teacher: url: jdbc:mysql://127.0.0.1:3306/teacher?useUnicode=true&characterEncoding=utf8&useSSL=false&tinyInt1isBit=true username: root password: 123456 #日誌 logging: config: classpath:log/logback.xml path: log/spring-boot-mybatis-datasource --- #測試環境配置 server: #端口 port: 80 spring: profiles: test # 數據源配置 datasource: student: url: jdbc:mysql://127.0.0.1:3306/student?useUnicode=true&characterEncoding=utf8&useSSL=false&tinyInt1isBit=true username: root password: 123456 teacher: url: jdbc:mysql://127.0.0.1:3306/teacher?useUnicode=true&characterEncoding=utf8&useSSL=false&tinyInt1isBit=true username: root password: 123456 #日誌 logging: config: classpath:log/logback.xml path: /home/log/spring-boot-mybatis-datasource --- #生產環境配置 server: #端口 port: 8080 spring: profiles: prod # 數據源配置 datasource: student: url: jdbc:mysql://127.0.0.1:3306/student?useUnicode=true&characterEncoding=utf8&useSSL=false&tinyInt1isBit=true username: root password: 123456 teacher: url: jdbc:mysql://127.0.0.1:3306/teacher?useUnicode=true&characterEncoding=utf8&useSSL=false&tinyInt1isBit=true username: root password: 123456 #日誌 logging: config: classpath:log/logback.xml path: /home/log/spring-boot-mybatis-datasource
這裏進行了mybatis
整合,若是不會mybatis
整合能夠參考我寫的這篇文章:
SpringBoot非官方教程 | 第六篇:SpringBoot整合mybatis web
在工程resources
文件夾下新建文件夾log
,並在該文件夾下建立logback.xml
文件,加入如下配置:spring
<!-- Logback configuration. See http://logback.qos.ch/manual/index.html --> <configuration scan="true" scanPeriod="10 seconds"> <!--繼承spring boot提供的logback配置--> <!--<include resource="org/springframework/boot/logging/logback/base.xml" />--> <!--設置系統日誌目錄--> <property name="APP_DIR" value="spring-boot-mybatis-datasource" /> <!-- 彩色日誌 --> <!-- 彩色日誌依賴的渲染類 --> <conversionRule conversionWord="clr" converterClass="org.springframework.boot.logging.logback.ColorConverter" /> <conversionRule conversionWord="wex" converterClass="org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter" /> <conversionRule conversionWord="wEx" converterClass="org.springframework.boot.logging.logback.ExtendedWhitespaceThrowableProxyConverter" /> <!-- 彩色日誌格式 --> <property name="CONSOLE_LOG_PATTERN" value="${CONSOLE_LOG_PATTERN:-%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(${LOG_LEVEL_PATTERN:-%5p}) %clr(${PID:- }){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n${LOG_EXCEPTION_CONVERSION_WORD:-%wEx}}"/> <!-- 控制檯輸出 --> <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <Pattern>${CONSOLE_LOG_PATTERN}</Pattern> <charset>UTF-8</charset> <!-- 此處設置字符集 --> </encoder> <!--此日誌appender是爲開發使用,只配置最底級別,控制檯輸出的日誌級別是大於或等於此級別的日誌信息--> <filter class="ch.qos.logback.classic.filter.ThresholdFilter"> <level>info</level> </filter> </appender> <!-- 時間滾動輸出 level爲 DEBUG 日誌 --> <appender name="DEBUG_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- 正在記錄的日誌文件的路徑及文件名 --> <file>${LOG_PATH}/log_debug.log</file> <!--日誌文件輸出格式--> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern> <charset>UTF-8</charset> <!-- 此處設置字符集 --> </encoder> <!-- 日誌記錄器的滾動策略,按日期,按大小記錄 --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- 歸檔的日誌文件的路徑,例現在天是2017-04-26日誌,當前寫的日誌文件路徑爲file節點指定,能夠將此文件與file指定文件路徑設置爲不一樣路徑,從而將當前日誌文件或歸檔日誌文件置不一樣的目錄。 而2017-04-26的日誌文件在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引 --> <fileNamePattern>${LOG_PATH}/debug/log-debug-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <!-- 除按日誌記錄以外,還配置了日誌文件不能超過500M,若超過500M,日誌文件會以索引0開始, 命名日誌文件,例如log-error-2017-04-26.0.log --> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>500MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> <!--日誌文件保留天數--> <maxHistory>30</maxHistory> </rollingPolicy> <!-- 此日誌文件只記錄debug級別的 --> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>debug</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> </appender> <!-- 時間滾動輸出 level爲 INFO 日誌 --> <appender name="INFO_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- 正在記錄的日誌文件的路徑及文件名 --> <file>${LOG_PATH}/log_info.log</file> <!--日誌文件輸出格式--> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern> <charset>UTF-8</charset> <!-- 此處設置字符集 --> </encoder> <!-- 日誌記錄器的滾動策略,按日期,按大小記錄 --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- 歸檔的日誌文件的路徑,例現在天是2017-04-26日誌,當前寫的日誌文件路徑爲file節點指定,能夠將此文件與file指定文件路徑設置爲不一樣路徑,從而將當前日誌文件或歸檔日誌文件置不一樣的目錄。 而2017-04-26的日誌文件在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引 --> <fileNamePattern>${LOG_PATH}/info/log-info-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <!-- 除按日誌記錄以外,還配置了日誌文件不能超過500M,若超過500M,日誌文件會以索引0開始, 命名日誌文件,例如log-error-2017-04-26.0.log --> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>500MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> <!--日誌文件保留天數--> <maxHistory>30</maxHistory> </rollingPolicy> <!-- 此日誌文件只記錄info級別的 --> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>info</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> </appender> <!-- 時間滾動輸出 level爲 WARN 日誌 --> <appender name="WARN_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- 正在記錄的日誌文件的路徑及文件名 --> <file>${LOG_PATH}/log_warn.log</file> <!--日誌文件輸出格式--> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern> <charset>UTF-8</charset> <!-- 此處設置字符集 --> </encoder> <!-- 日誌記錄器的滾動策略,按日期,按大小記錄 --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- 歸檔的日誌文件的路徑,例現在天是2017-04-26日誌,當前寫的日誌文件路徑爲file節點指定,能夠將此文件與file指定文件路徑設置爲不一樣路徑,從而將當前日誌文件或歸檔日誌文件置不一樣的目錄。 而2017-04-26的日誌文件在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引 --> <fileNamePattern>${LOG_PATH}/warn/log-warn-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <!-- 除按日誌記錄以外,還配置了日誌文件不能超過500M,若超過500M,日誌文件會以索引0開始, 命名日誌文件,例如log-error-2017-04-26.0.log --> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>500MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> <!--日誌文件保留天數--> <maxHistory>30</maxHistory> </rollingPolicy> <!-- 此日誌文件只記錄warn級別的 --> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>warn</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> </appender> <!-- 時間滾動輸出 level爲 ERROR 日誌 --> <appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- 正在記錄的日誌文件的路徑及文件名 --> <file>${LOG_PATH}/log_error.log</file> <!--日誌文件輸出格式--> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern> <charset>UTF-8</charset> <!-- 此處設置字符集 --> </encoder> <!-- 日誌記錄器的滾動策略,按日期,按大小記錄 --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- 歸檔的日誌文件的路徑,例現在天是2017-04-26日誌,當前寫的日誌文件路徑爲file節點指定,能夠將此文件與file指定文件路徑設置爲不一樣路徑,從而將當前日誌文件或歸檔日誌文件置不一樣的目錄。 而2017-04-26的日誌文件在由fileNamePattern指定。%d{yyyy-MM-dd}指定日期格式,%i指定索引 --> <fileNamePattern>${LOG_PATH}/error/log-error-%d{yyyy-MM-dd}.%i.log</fileNamePattern> <!-- 除按日誌記錄以外,還配置了日誌文件不能超過500M,若超過500M,日誌文件會以索引0開始, 命名日誌文件,例如log-error-2017-04-26.0.log --> <timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP"> <maxFileSize>500MB</maxFileSize> </timeBasedFileNamingAndTriggeringPolicy> <!--日誌文件保留天數--> <maxHistory>30</maxHistory> </rollingPolicy> <!-- 此日誌文件只記錄ERROR級別的 --> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>error</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> </appender> <logger name="org.springframework.web" level="info"/> <logger name="org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor" level="INFO"/> <logger name="cn.zhangbox.springboot" level="debug"/> <!--開發環境:打印控制檯--> <springProfile name="dev"> <root level="info"> <appender-ref ref="CONSOLE" /> <appender-ref ref="DEBUG_FILE" /> <appender-ref ref="INFO_FILE" /> <appender-ref ref="WARN_FILE" /> <appender-ref ref="ERROR_FILE" /> </root> </springProfile> <!--測試環境:打印控制檯和輸出到文件--> <springProfile name="test"> <root level="info"> <appender-ref ref="CONSOLE" /> <appender-ref ref="INFO_FILE" /> <appender-ref ref="WARN_FILE" /> <appender-ref ref="ERROR_FILE" /> </root> </springProfile> <!--生產環境:輸出到文件--> <springProfile name="prod"> <root level="info"> <appender-ref ref="DEBUG_FILE" /> <appender-ref ref="INFO_FILE" /> <appender-ref ref="ERROR_FILE" /> </root> </springProfile> </configuration>
注意::loback
配置文件中sql
<logger name="cn.zhangbox.springboot" level="debug"/>
name
的屬性值必定要是當前工程的java
代碼的完整目錄,由於mybatis
打印的日誌級別是debug
級別的,所以須要配置debug
級別日誌掃描的目錄。數據庫
在工程java
代碼目錄下建立config
的目錄在下面建立DruidDBConfig
類加入如下代碼:
@Configuration public class DruidDBConfig { @Bean public ServletRegistrationBean druidServlet() { ServletRegistrationBean reg = new ServletRegistrationBean(); reg.setServlet(new StatViewServlet()); reg.addUrlMappings("/druid/*"); //設置控制檯管理用戶 reg.addInitParameter("loginUsername","root"); reg.addInitParameter("loginPassword","root"); // 禁用HTML頁面上的「Reset All」功能 reg.addInitParameter("resetEnable","false"); //reg.addInitParameter("allow", "127.0.0.1"); //白名單 return reg; } @Bean public FilterRegistrationBean filterRegistrationBean() { //建立過濾器 FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new WebStatFilter()); Map<String, String> initParams = new HashMap<String, String>(); //忽略過濾的形式 initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"); filterRegistrationBean.setInitParameters(initParams); //設置過濾器過濾路徑 filterRegistrationBean.addUrlPatterns("/*"); return filterRegistrationBean; } }
注意:這裏ServletRegistrationBean
配置bean中經過addInitParameter
設置了管控臺的用戶名密碼都是root
,能夠在這裏進行自定義配置也能夠將這裏的用戶名密碼經過轉移數據庫進行定製化配置實現。
在工程java
代碼目錄下建立config
的目錄在下面建立StudentDataSourceConfig
類加入如下代碼:
@Configuration @MapperScan(basePackages ="cn.zhangbox.springboot.dao.student",sqlSessionFactoryRef = "studentSqlSessionFactory")//mybatis接口包掃描 public class StudentDataSourceConfig { @Value("${spring.datasource.student.type}") private Class<? extends DataSource> dataSourceType; /** *初始化鏈接池 * @return */ @Bean(name = "studentDataSource") @ConfigurationProperties(prefix = "spring.datasource.student") @Primary public DataSource writeDataSource() { return DataSourceBuilder.create().type(dataSourceType).build(); } /** * * 構建 SqlSessionFactory * @return */ @Bean(name = "studentSqlSessionFactory") @Primary public SqlSessionFactory studentSqlSessionFactory(@Qualifier("studentDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); //bean.setTypeAliasesPackage("com.ztzq.data.beans.bigdata"); bean.setVfs(SpringBootVFS.class); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/student/*.xml")); return bean.getObject(); } /** * 配置事物 * @param dataSource * @return */ @Bean(name = "studentTransactionManager") @Primary public DataSourceTransactionManager TransactionManager(@Qualifier("studentDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } /** * 構建 SqlSessionTemplate * @param sqlSessionFactory * @return * @throws Exception */ @Bean(name = "studentSqlSessionTemplate") @Primary public SqlSessionTemplate SqlSessionTemplate(@Qualifier("studentSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } }
在工程java
代碼目錄下建立config
的目錄在下面建立TeacherDataSourceConfig
類加入如下代碼:
@Configuration @MapperScan(basePackages ="cn.zhangbox.springboot.dao.teacher",sqlSessionFactoryRef = "teacherSqlSessionFactory")//mybatis接口包掃描 public class TecaherDataSourceConfig { @Value("${spring.datasource.teacher.type}") private Class<? extends DataSource> dataSourceType; /** *初始化鏈接池 * @return */ @Bean(name = "teacherDataSource") @ConfigurationProperties(prefix = "spring.datasource.teacher") public DataSource writeDataSource() { return DataSourceBuilder.create().type(dataSourceType).build(); } /** * * 構建 SqlSessionFactory * @return */ @Bean(name = "teacherSqlSessionFactory") public SqlSessionFactory teacherSqlSessionFactory(@Qualifier("teacherDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); //bean.setTypeAliasesPackage("com.ztzq.data.beans.bigdata"); bean.setVfs(SpringBootVFS.class); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/teacher/*.xml")); return bean.getObject(); } /** * 配置事物 * @param dataSource * @return */ @Bean(name = "teacherTransactionManager") public DataSourceTransactionManager TransactionManager(@Qualifier("teacherDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } /** * 構建 SqlSessionTemplate * @param sqlSessionFactory * @return * @throws Exception */ @Bean(name = "teacherSqlSessionTemplate") public SqlSessionTemplate SqlSessionTemplate(@Qualifier("teacherSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception { return new SqlSessionTemplate(sqlSessionFactory); } }
在工程java
代碼目錄下建立entity
的目錄在下面建立Student
類加入如下代碼:
@Data @EqualsAndHashCode(callSuper = false) public class Student { private static final long serialVersionUID = 1L; /** * 主鍵id */ private Integer sno; /** * 學生姓名 */ private String sname; /** * 性別 */ private String sex; /** * 生日 */ private String birth; /** * 年齡 */ private String age; /** * 簡介 */ private String dept; }
在工程java
代碼目錄下建立entity
的目錄在下面建立Teacher
類加入如下代碼:
@Data @EqualsAndHashCode(callSuper = false) public class Teacher { private static final long serialVersionUID = 1L; /** * 主鍵id */ private Integer tno; /** * 老師姓名 */ private String tname; /** * 性別 */ private String sex; /** * 生日 */ private String birth; /** * 年齡 */ private String age; /** * 簡介 */ private String dept; }
在工程java
代碼目錄下建立controller
的目錄在下面建立StudentConteroller
類加入如下代碼:
@Controller @RequestMapping("/student") public class StudentConteroller { private static final Logger LOGGER = LoggerFactory.getLogger(StudentConteroller.class); @Autowired protected StudentService studentService; /** * 查詢全部的學生信息 * * @param sname * @param age * @param modelMap * @return */ @ResponseBody @GetMapping("/list") public String list(String sname, Integer age, ModelMap modelMap) { String json = null; try { List<Student> studentList = studentService.getStudentList(sname, age); modelMap.put("ren_code", "0"); modelMap.put("ren_msg", "查詢成功"); modelMap.put("studentList", studentList); json = JSON.toJSONString(modelMap); } catch (Exception e) { e.printStackTrace(); modelMap.put("ren_code", "0"); modelMap.put("ren_msg", "查詢失敗===>" + e); LOGGER.error("查詢失敗===>" + e); json = JSON.toJSONString(modelMap); } return json; } }
在工程java
代碼目錄下建立controller
的目錄在下面建立TeacherConteroller
類加入如下代碼:
@Controller @RequestMapping("/teacher") public class TeacherConteroller { private static final Logger LOGGER = LoggerFactory.getLogger(TeacherConteroller.class); @Autowired protected TeacherService teacherService; /** * 查詢全部的老師信息 * * @param tname * @param age * @param modelMap * @return */ @ResponseBody @GetMapping("/list") public String list(String tname, Integer age, ModelMap modelMap) { String json = null; try { List<Teacher> teacherList = teacherService.getTeacherList(tname, age); modelMap.put("ren_code", "0"); modelMap.put("ren_msg", "查詢成功"); modelMap.put("teacherList", teacherList); json = JSON.toJSONString(modelMap); } catch (Exception e) { e.printStackTrace(); modelMap.put("ren_code", "0"); modelMap.put("ren_msg", "查詢失敗===>" + e); LOGGER.error("查詢失敗===>" + e); json = JSON.toJSONString(modelMap); } return json; } }
在工程java
代碼目錄下面建立service
目錄在下面建立StudentService
類加入如下代碼:
public interface StudentService { /** * 查詢全部的學生信息 * * @param sname * @param age * @return */ List<Student> getStudentList(String sname, Integer age); }
在工程java
代碼目錄下面建立service
目錄在下面建立TeacherService
類加入如下代碼:
public interface TeacherService { /** * 查詢全部的老師信息 * * @param tname * @param age * @return */ List<Teacher> getTeacherList(String tname, Integer age); }
在工程java
代碼目錄下的service
的目錄下面建立impl
目錄在下面建立StudentServiceImpl
類加入如下代碼:
@Service("StudentService") @Transactional(readOnly = true, rollbackFor = Exception.class) public class StudentServiceImpl implements StudentService { @Autowired StudentDao studentDao; @Override public List<Student> getStudentList(String sname, Integer age) { return studentDao.getStudentList(sname,age); } }
在工程java
代碼目錄下的service
的目錄下面建立impl
目錄在下面建立TeacherServiceImpl
類加入如下代碼:
@Service("TeacherService") @Transactional(readOnly = true, rollbackFor = Exception.class) public class TeacherServiceImpl implements TeacherService { @Autowired TeacherDao teacherDao; @Override public List<Teacher> getTeacherList(String tname, Integer age) { return teacherDao.getTeacherList(tname,age); } }
在工程java
代碼目錄下建立dao
的目錄下面建立student
目錄在此目錄下建立StudentDao
類加入如下代碼:
public interface StudentDao { List<Student> getStudentList(@Param("sname")String sname, @Param("age")Integer age); }
在工程java
代碼目錄下建立dao
的目錄下面建立teacher
目錄在此目錄下建立TeacherDao
類加入如下代碼:
public interface TeacherDao { List<Teacher> getTeacherList(@Param("tname") String tname, @Param("age") Integer age); }
在工程resource
目錄下建立mapper
的目錄下建立student
目錄在此目錄下面建立StudentMapper.xml
映射文件加入如下代碼:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="cn.zhangbox.springboot.dao.StudentDao" > <!-- 查詢全部的學生信息 --> <select id="getStudentList" resultType="cn.zhangbox.springboot.entity.Student"> SELECT s.sno, s.sname, s.sex, s.dept, s.birth, s.age FROM student s WHERE 1 = 1 <if test="sname != null"> and s.sname = #{sname} </if> <if test="age != null"> and s.age = #{age} </if> </select> </mapper>
在工程resource
目錄下建立mapper
的目錄下建立teacher
目錄在此目錄下面建立TeacherMapper.xml
映射文件加入如下代碼:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="cn.zhangbox.springboot.dao.teacher.TeacherDao" > <!-- 查詢全部的老師信息 --> <select id="getTeacherList" resultType="cn.zhangbox.springboot.entity.Teacher"> SELECT s.tno, s.tname, s.sex, s.dept, s.birth, s.age FROM teacher s WHERE 1 = 1 <if test="tname != null"> and s.tname = #{tname} </if> <if test="age != null"> and s.age = #{age} </if> </select> </mapper>
@SpringBootApplication public class SpringBootManyDataSourceApplication extends SpringBootServletInitializer { public static void main(String[] args) { SpringApplication.run(SpringBootManyDataSourceApplication.class, args); } }
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.5.3.RELEASE) 2018-07-09 19:58:22.757 INFO 10096 --- [ main] .z.s.SpringBootManyDataSourceApplication : Starting SpringBootManyDataSourceApplication on 99IHXFJDHAQ7H7N with PID 10096 (started by Administrator in D:\開源項目\spring-boot-study) 2018-07-09 19:58:22.780 INFO 10096 --- [ main] .z.s.SpringBootManyDataSourceApplication : The following profiles are active: dev 2018-07-09 19:58:22.987 INFO 10096 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@35e5d0e5: startup date [Mon Jul 09 19:58:22 CST 2018]; root of context hierarchy 2018-07-09 19:58:23.460 INFO 10096 --- [kground-preinit] o.h.validator.internal.util.Version : HV000001: Hibernate Validator 5.3.5.Final 2018-07-09 19:58:24.220 INFO 10096 --- [ main] o.s.b.f.s.DefaultListableBeanFactory : Overriding bean definition for bean 'filterRegistrationBean' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=druidDBConfig; factoryMethodName=filterRegistrationBean; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [cn/zhangbox/springboot/config/DruidDBConfig.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=com.alibaba.druid.spring.boot.autoconfigure.stat.DruidWebStatFilterConfiguration; factoryMethodName=filterRegistrationBean; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/alibaba/druid/spring/boot/autoconfigure/stat/DruidWebStatFilterConfiguration.class]] 2018-07-09 19:58:25.440 INFO 10096 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http) 2018-07-09 19:58:25.457 INFO 10096 --- [ main] o.apache.catalina.core.StandardService : Starting service Tomcat 2018-07-09 19:58:25.459 INFO 10096 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.14 2018-07-09 19:58:25.594 INFO 10096 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2018-07-09 19:58:25.594 INFO 10096 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 2608 ms 2018-07-09 19:58:26.138 INFO 10096 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'statViewServlet' to [/druid/*] 2018-07-09 19:58:26.139 INFO 10096 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/] 2018-07-09 19:58:26.140 INFO 10096 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Mapping servlet: 'statViewServlet' to [/druid/*] 2018-07-09 19:58:26.141 INFO 10096 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean : Servlet statViewServlet was not registered (possibly already registered?) 2018-07-09 19:58:26.146 INFO 10096 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'characterEncodingFilter' to: [/*] 2018-07-09 19:58:26.147 INFO 10096 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*] 2018-07-09 19:58:26.148 INFO 10096 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'httpPutFormContentFilter' to: [/*] 2018-07-09 19:58:26.148 INFO 10096 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'requestContextFilter' to: [/*] 2018-07-09 19:58:26.149 INFO 10096 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean : Mapping filter: 'webStatFilter' to urls: [/*] 2018-07-09 19:58:27.694 INFO 10096 --- [ main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@35e5d0e5: startup date [Mon Jul 09 19:58:22 CST 2018]; root of context hierarchy 2018-07-09 19:58:27.792 INFO 10096 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/student/list],methods=[GET]}" onto public java.lang.String cn.zhangbox.springboot.controller.StudentConteroller.list(java.lang.String,java.lang.Integer,org.springframework.ui.ModelMap) 2018-07-09 19:58:27.794 INFO 10096 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/teacher/list],methods=[GET]}" onto public java.lang.String cn.zhangbox.springboot.controller.TeacherConteroller.list(java.lang.String,java.lang.Integer,org.springframework.ui.ModelMap) 2018-07-09 19:58:27.796 INFO 10096 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest) 2018-07-09 19:58:27.796 INFO 10096 --- [ main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse) 2018-07-09 19:58:27.837 INFO 10096 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2018-07-09 19:58:27.837 INFO 10096 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2018-07-09 19:58:27.893 INFO 10096 --- [ main] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2018-07-09 19:58:28.836 INFO 10096 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup 2018-07-09 19:58:28.837 INFO 10096 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'studentDataSource' has been autodetected for JMX exposure 2018-07-09 19:58:28.838 INFO 10096 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'teacherDataSource' has been autodetected for JMX exposure 2018-07-09 19:58:28.838 INFO 10096 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'statFilter' has been autodetected for JMX exposure 2018-07-09 19:58:28.846 INFO 10096 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'studentDataSource': registering with JMX server as MBean [com.alibaba.druid.pool:name=studentDataSource,type=DruidDataSource] 2018-07-09 19:58:28.849 INFO 10096 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'teacherDataSource': registering with JMX server as MBean [com.alibaba.druid.pool:name=teacherDataSource,type=DruidDataSource] 2018-07-09 19:58:28.851 INFO 10096 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Located MBean 'statFilter': registering with JMX server as MBean [com.alibaba.druid.filter.stat:name=statFilter,type=StatFilter] 2018-07-09 19:58:28.877 INFO 10096 --- [ main] o.a.coyote.http11.Http11NioProtocol : Initializing ProtocolHandler ["http-nio-8080"] 2018-07-09 19:58:28.905 INFO 10096 --- [ main] o.a.coyote.http11.Http11NioProtocol : Starting ProtocolHandler ["http-nio-8080"] 2018-07-09 19:58:28.930 INFO 10096 --- [ main] o.a.tomcat.util.net.NioSelectorPool : Using a shared selector for servlet write/read 2018-07-09 19:58:28.965 INFO 10096 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http) 2018-07-09 19:58:28.972 INFO 10096 --- [ main] .z.s.SpringBootManyDataSourceApplication : Started SpringBootManyDataSourceApplication in 8.519 seconds (JVM running for 12.384) 2018-07-09 19:58:37.626 INFO 10096 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet' 2018-07-09 19:58:37.626 INFO 10096 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started 2018-07-09 19:58:37.660 INFO 10096 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 33 ms 2018-07-09 19:58:37.981 INFO 10096 --- [nio-8080-exec-1] com.alibaba.druid.pool.DruidDataSource : {dataSource-1} inited 2018-07-09 19:58:41.381 INFO 10096 --- [nio-8080-exec-2] com.alibaba.druid.pool.DruidDataSource : {dataSource-2} inited
2018-07-09 19:58:22.779 [main] DEBUG c.z.springboot.SpringBootManyDataSourceApplication - Running with Spring Boot v1.5.3.RELEASE, Spring v4.3.8.RELEASE 2018-07-09 19:58:38.386 [http-nio-8080-exec-1] DEBUG c.z.s.dao.student.StudentDao.getStudentList - ==> Preparing: SELECT s.sno, s.sname, s.sex, s.dept, s.birth, s.age FROM student s WHERE 1 = 1 2018-07-09 19:58:38.409 [http-nio-8080-exec-1] DEBUG c.z.s.dao.student.StudentDao.getStudentList - ==> Parameters: 2018-07-09 19:58:38.436 [http-nio-8080-exec-1] DEBUG c.z.s.dao.student.StudentDao.getStudentList - <== Total: 2 2018-07-09 19:58:41.461 [http-nio-8080-exec-2] DEBUG c.z.s.dao.teacher.TeacherDao.getTeacherList - ==> Preparing: SELECT s.tno, s.tname, s.sex, s.dept, s.birth, s.age FROM teacher s WHERE 1 = 1 2018-07-09 19:58:41.462 [http-nio-8080-exec-2] DEBUG c.z.s.dao.teacher.TeacherDao.getTeacherList - ==> Parameters: 2018-07-09 19:58:41.472 [http-nio-8080-exec-2] DEBUG c.z.s.dao.teacher.TeacherDao.getTeacherList - <== Total: 1
這裏使用logback
配置中將不一樣級別的日誌設置了在不一樣文件中打印,這樣很大程度上方便項目出問題查找問題。
druid
連接池不知道怎麼配置能夠參考我寫的這篇文章:
SpringBoot進階教程 | 第三篇:整合Druid鏈接池以及Druid監控
歡迎關注個人微信公衆號獲取更多更全的學習資源,視頻資料,技術乾貨!