springboot整合mybatis使用阿里(阿里連接池)和xml方式


源碼地址:https://github.com/wuhongpu/springboot-mybatis.git

1、在pom文件中引入相關依賴包

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <groupId>zytl.zytrade.cloud</groupId>
  <artifactId>zytrade-sevice-mobile</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>zytrade-sevice-mobile</name>
  <url>http://maven.apache.org</url>
<!--引入Springboot依賴包-->
 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!--eureka依賴-->
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-eureka</artifactId>
    </dependency>
    <!-- 監控生產環境模塊 -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
     <!--支持Spring依賴包-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
    </dependency>
    <!--支持springmvc包-->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--mybatis依賴包-->
    <dependency>
      <groupId>org.mybatis.spring.boot</groupId>
      <artifactId>mybatis-spring-boot-starter</artifactId>
      <version>1.3.0</version>
    </dependency>
    <!-- oracle驅動 -->
    <dependency>
      <groupId>org.oracle</groupId>
      <artifactId>oracle</artifactId>
      <version>11.2</version>
    </dependency>
    <!-- 阿里連接池-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.0.18</version>
    </dependency>
    <!-- log4j2 riz日志包-->
     <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-log4j2</artifactId>
     </dependency>
    <!-- gson驅動包-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.16</version>
    </dependency>
  </dependencies>

</project>

2、配置文件application.yml

mysql和阿里druid配置
spring:
  application:
    name: zytrade-sevice-mobile    #指定應用的名稱建議使用小寫
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    url: jdbc:oracle:thin:@192.168.1.98:1521:orcl
    #url: jdbc:mysql://localhost/test?useSSL=false&serverTimezone=UTC
    username: proOne
    password: proOne123
    #username: root
   #password: 123456
    #driver-class-name: com.mysql.jdbc.Driver
    driver-class-name: oracle.jdbc.driver.OracleDriver
    # 下面為連接池的補充設置,應用到上面所有數據源中
    # 初始化大小,最小,最大
    initialSize: 1
    minIdle: 3
    maxActive: 20
    # 配置獲取連接等待超時的時間
    maxWait: 60000
    # 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒
    timeBetweenEvictionRunsMillis: 60000
    # 配置一個連接在池中最小生存的時間,單位是毫秒
    minEvictableIdleTimeMillis: 30000
    #validationQuery: select 'x'
    testWhileIdle: false
    testOnBorrow: false
    testOnReturn: false
    # 打開PSCache,並且指定每個連接上PSCache的大小
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20
    # 配置監控統計攔截的filters,去掉后監控界面sql無法統計,'wall'用於防火牆
    filters: stat,wall,slf4j
    # 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
    # 合並多個DruidDataSource的監控數據
    useGlobalDataSourceStat: true

# mybatis配置
mybatis:
  mapper-locations: classpath*:/zytrade.service.mobile/*.xml

3、啟動類

/**
 * @Author: wu
 * @Description:
 * @Date: Create in 11:19 2017/11/8
 * @Modified By:
 */
@SpringBootApplication
@EnableAutoConfiguration
//@EnableDiscoveryClient
@MapperScan("zytrade.service.mobile.dao")//接口掃描,如果此處不加@MapperScan注解必須在接口類上添加@Mapper注解表明這是一個接口掃描器
 
         
public class MposApplication { public static void main(String[] args) { SpringApplication.run(MposApplication.class, args); } }

4、阿里數據池配置類

package zytrade.service.mobile.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class DruidDataSourceConfiguration { @Bean @ConfigurationProperties(prefix = "spring.datasource") public DataSource druidDataSource() { DruidDataSource druidDataSource = new DruidDataSource(); return druidDataSource; } // @Bean // public HttpMessageConverters fastJsonHttpMessageConverters(){ // FastJsonHttpMessageConverter fastConverter=new FastJsonHttpMessageConverter(); // FastJsonConfig fastJsonConfig=new FastJsonConfig(); // fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); // fastConverter.setFastJsonConfig(fastJsonConfig); // HttpMessageConverter<?> converter = fastConverter; // return new HttpMessageConverters(converter); // } }

2、

package zytrade.service.mobile.config;
import com.alibaba.druid.support.http.WebStatFilter;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

@WebFilter(filterName="druidWebStatFilter",urlPatterns="/*", initParams={ @WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")// 忽略資源 } ) public class DruidStatFilter extends WebStatFilter { }

3

package zytrade.service.mobile.config;
import com.alibaba.druid.support.http.StatViewServlet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.annotation.WebInitParam;
@WebServlet(urlPatterns = "/druid/*", 
    initParams={
            @WebInitParam(name="allow",value="192.168.16.110,127.0.0.1"),// IP白名單 (沒有配置或者為空,則允許所有訪問)
            @WebInitParam(name="deny",value="192.168.16.111"),// IP黑名單 (存在共同時,deny優先於allow)
            @WebInitParam(name="loginUsername",value="admin"),// 用戶名
            @WebInitParam(name="loginPassword",value="123"),// 密碼
            @WebInitParam(name="resetEnable",value="false")// 禁用HTML頁面上的“Reset All”功能
    })
public class DruidStatViewServlet extends StatViewServlet {
    private static final long serialVersionUID = 1L;
    
}

5、項目視圖

 

補充log4j2.xml與 mybatis-conf.xml(mybatis全局配置文件)

1、log4j2.xml

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <properties>
        <!-- 文件輸出格式 -->
        <property name="PATTERN">%d{yyyy-MM-dd HH:mm:ss.SSS} |-%-5level [%thread] %c [%L] -| %msg%n</property>
    </properties>

    <appenders>
        <Console name="Console" target="system_out">
            <PatternLayout pattern="${PATTERN}" />
        </Console>
    </appenders>
    <!--配置mybatis日志 -->
    <loggers>

        <logger name="log4j.logger.org.mybatis" level="debug"
            additivity="false">
            <appender-ref ref="Console" />
        </logger>
        <logger name="log4j.logger.java.sql" level="debug" additivity="false">
            <appender-ref ref="Console" />
        </logger>
        <logger name="com.demo.mapper" level="debug" />
        <root level="info">
            <appenderref ref="Console" />
        </root>
    </loggers>

</configuration>

2、 mybatis-conf.xml

 

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright 2015-2016 the original author or authors. Licensed under the 
    Apache License, Version 2.0 (the "License"); you may not use this file except 
    in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 
    Unless required by applicable law or agreed to in writing, software distributed 
    under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES 
    OR CONDITIONS OF ANY KIND, either express or implied. See the License for 
    the specific language governing permissions and limitations under the License. -->
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--設置mybatis日志類型 -->
    <settings>
        <setting name="logImpl" value="LOG4J2" />
        <!--配置的緩存的全局開關。 -->
        <setting name="cacheEnabled" value="true" />
        <!--延遲加載的全局開關。當開啟時,所有關聯對象都會延遲加載。 特定關聯關系中可通過設置fetchType屬性來覆蓋該項的開關狀態。 -->
        <setting name="lazyLoadingEnabled" value="true" />
        <!--當沒有為參數提供特定的 JDBC 類型時,為空值指定 JDBC 類型。 某些驅動需要指定列的 JDBC 類型,多數情況直接用一般類型即可,比如 
            NULL、VARCHAR 或 OTHER。 -->
        <setting name="jdbcTypeForNull" value="NULL" />

    </settings>
</configuration>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM