springboot整合druid、mybatis和配置PageHelper分頁插件以及配置log日誌

整合druid

修改SpringBoot的數據源Druid(默認數據源是org.apache.tomcat.jdbc.pool.DataSource)

1>引入依賴

  <dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>druid-spring-boot-starter</artifactId>
     <version>1.1.10</version>
  </dependency>

2>配置application.yml

spring:
  datasource:
    #1.JDBC
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/mydatabase?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123
    druid:
      #2.連接池配置
      #初始化連接池的連接數量 大小,最小,最大
      initial-size: 5
      min-idle: 5
      max-active: 20
      #配置獲取連接等待超時的時間
      max-wait: 60000
      #配置間隔多久才進行一次檢測,檢測需要關閉的空閒連接,單位是毫秒
      time-between-eviction-runs-millis: 60000
      # 配置一個連接在池中最小生存的時間,單位是毫秒
      min-evictable-idle-time-millis: 30000
      validation-query: SELECT 1 FROM DUAL
      test-while-idle: true
      test-on-borrow: true
      test-on-return: false
      # 是否緩存preparedStatement,也就是PSCache  官方建議MySQL下建議關閉   個人建議如果想用SQL防火牆 建議打開
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      # 配置監控統計攔截的filters,去掉後監控界面sql無法統計,'wall'用於防火牆
      filter:
        stat:
          merge-sql: true
          slow-sql-millis: 5000
      #3.基礎監控配置
      web-stat-filter:
        enabled: true
        url-pattern: /*
        #設置不統計哪些URL
        exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
        session-stat-enable: true
        session-stat-max-count: 100
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*
        reset-enable: true
        #設置監控頁面的登錄名和密碼
        login-username: admin
        login-password: admin
        allow: 127.0.0.1
        #deny: 192.168.1.100

3> 啓動SpringBoot項目訪問druid
  
  http://localhost:tomcat端口號/項目名稱/druid/

出現界面

使用設置好的賬號密碼登陸即可查看

 

整合mybatis

1> 引入依賴

<dependency>
     <groupId>org.mybatis.spring.boot</groupId>
     <artifactId>mybatis-spring-boot-starter</artifactId>
     <version>1.3.2</version>
  </dependency>

 MyBatis-Spring-Boot-Starter依賴將會提供如下:
   自動檢測現有的DataSource。
   將創建並註冊SqlSessionFactory的實例,該實例使用SqlSessionFactoryBean將該DataSource作爲輸入進行傳遞。
   將創建並註冊從SqlSessionFactory中獲取的SqlSessionTemplate的實例。
   自動掃描您的mappers,將它們鏈接到SqlSessionTemplate並將其註冊到Spring上下文,以便將它們注入到您的bean中。

  就是說,使用了該Starter之後,只需要定義一個DataSource即可(application.properties或application.yml中可配置),它會自動創建使用該DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。會自動掃描你的Mappers,連接到SqlSessionTemplate,並註冊到Spring上下文中。
 

2>配置application.yml

 mybatis:
     #配置SQL映射文件路徑
     mapper-locations: classpath:mapper/*.xml
     #配置別名
     type-aliases-package: com.項目名.model
  

3>使用Mybatis-Generator插件生成代碼

需要的配置文件

pom.xml 需要添加的代碼

<resources>
    <!--解決mybatis-generator-maven-plugin運行時沒有將XxxMapper.xml文件放入target文件夾的問題-->
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
     </resource>
     <!--解決mybatis-generator-maven-plugin運行時沒有將jdbc.properites文件放入target文件夾的問題-->
     <resource>
         <directory>src/main/resources</directory>
         <includes>
             <include>jdbc.properties</include>
             <include>*.xml</include>
         </includes>
     </resource>
 </resources>

/*******************************************************************************/
 <plugin>
     <groupId>org.mybatis.generator</groupId>
     <artifactId>mybatis-generator-maven-plugin</artifactId>
     <version>1.3.2</version>
     <dependencies>
         <!--使用Mybatis-generator插件不能使用太高版本的mysql驅動 -->
         <dependency>
              <groupId>mysql</groupId>
              <artifactId>mysql-connector-java</artifactId>
              <version>5.1.44</version>
         </dependency>
     </dependencies>
     <configuration>
         <overwrite>true</overwrite>
     </configuration>
 </plugin>

需要的資源文件

generatorConfiguration.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd" >
<generatorConfiguration>
    <!-- 引入配置文件 -->
    <properties resource="jdbc.properties"/>

    <!--指定數據庫jdbc驅動jar包的位置-->
    <classPathEntry location="D:\initPath\mvn_repository\mysql\mysql-connector-java\5.1.44\mysql-connector-java-5.1.44.jar"/>

    <!-- 一個數據庫一個context -->
    <context id="infoGuardian">
        <!-- 註釋 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/><!-- 是否取消註釋 -->
            <property name="suppressDate" value="true"/> <!-- 是否生成註釋代時間戳 -->
        </commentGenerator>

        <!-- jdbc連接 -->
        <jdbcConnection driverClass="${jdbc.driver}"
                        connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>

        <!-- 類型轉換 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自動轉化以下類型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- 01 指定javaBean生成的位置 -->
        <!-- targetPackage:指定生成的model生成所在的包名 -->
        <!-- targetProject:指定在該項目下所在的路徑  -->
        <javaModelGenerator targetPackage="com.javaxl.p1.entity"
                            targetProject="src/main/java">
            <!-- 是否允許子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否對model添加構造函數 -->
            <property name="constructorBased" value="true"/>
            <!-- 是否針對string類型的字段在set的時候進行trim調用 -->
            <property name="trimStrings" value="false"/>
            <!-- 建立的Model對象是否 不可改變  即生成的Model對象不會有 setter方法,只有構造方法 -->
            <property name="immutable" value="false"/>
        </javaModelGenerator>

        <!-- 02 指定sql映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="com.javaxl.p1.mapper"
                         targetProject="src/main/java">
            <!-- 是否允許子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!-- 03 生成XxxMapper接口 -->
        <!-- type="ANNOTATEDMAPPER",生成Java Model 和基於註解的Mapper對象 -->
        <!-- type="MIXEDMAPPER",生成基於註解的Java Model 和相應的Mapper對象 -->
        <!-- type="XMLMAPPER",生成SQLMap XML文件和獨立的Mapper接口 -->
        <javaClientGenerator targetPackage="com.javaxl.p1.mapper"
                             targetProject="src/main/java" type="XMLMAPPER">
            <!-- 是否在當前路徑下新加一層schema,false路徑com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>

        <!-- 配置表信息 -->
        <!-- schema即爲數據庫名 -->
        <!-- tableName爲對應的數據庫表 -->
        <!-- domainObjectName是要生成的實體類 -->
        <!-- enable*ByExample是否生成 example類 -->
        <!--<table schema="" tableName="t_book" domainObjectName="Book"-->
               <!--enableCountByExample="false" enableDeleteByExample="false"-->
               <!--enableSelectByExample="false" enableUpdateByExample="false">-->
            <!--&lt;!&ndash; 忽略列,不生成bean 字段 &ndash;&gt;-->
            <!--&lt;!&ndash; <ignoreColumn column="FRED" /> &ndash;&gt;-->
            <!--&lt;!&ndash; 指定列的java數據類型 &ndash;&gt;-->
            <!--&lt;!&ndash; <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> &ndash;&gt;-->
        <!--</table>-->

        <!--<table schema="" tableName="t_p1_user" domainObjectName="User"-->
               <!--enableCountByExample="false" enableDeleteByExample="false"-->
               <!--enableSelectByExample="false" enableUpdateByExample="false">-->
            <!--<property name="useActualColumnNames" value="true" />-->
        <!--</table>-->

        <!--<table schema="" tableName="t_p1_role" domainObjectName="Role"-->
               <!--enableCountByExample="false" enableDeleteByExample="false"-->
               <!--enableSelectByExample="false" enableUpdateByExample="false">-->
            <!--<property name="useActualColumnNames" value="true" />-->
        <!--</table>-->

        <!--<table schema="" tableName="t_p1_permission" domainObjectName="Permission"-->
               <!--enableCountByExample="false" enableDeleteByExample="false"-->
               <!--enableSelectByExample="false" enableUpdateByExample="false">-->
            <!--<property name="useActualColumnNames" value="true" />-->
        <!--</table>-->

        <!--<table schema="" tableName="t_p1_user_role" domainObjectName="UserRole"-->
               <!--enableCountByExample="false" enableDeleteByExample="false"-->
               <!--enableSelectByExample="false" enableUpdateByExample="false">-->
            <!--<property name="useActualColumnNames" value="true" />-->
        <!--</table>-->

        <!--<table schema="" tableName="t_p1_role_permission" domainObjectName="RolePermission"-->
               <!--enableCountByExample="false" enableDeleteByExample="false"-->
               <!--enableSelectByExample="false" enableUpdateByExample="false">-->
            <!--<property name="useActualColumnNames" value="true" />-->
        <!--</table>-->

        <!--<table schema="" tableName="t_p1_blog" domainObjectName="Blog"-->
               <!--enableCountByExample="false" enableDeleteByExample="false"-->
               <!--enableSelectByExample="false" enableUpdateByExample="false">-->
            <!--<property name="useActualColumnNames" value="true" />-->
        <!--</table>-->

        <!--<table schema="" tableName="t_p1_blogtype" domainObjectName="BlogType"-->
               <!--enableCountByExample="false" enableDeleteByExample="false"-->
               <!--enableSelectByExample="false" enableUpdateByExample="false">-->
            <!--<property name="useActualColumnNames" value="true" />-->
        <!--</table>-->

        <!--<table schema="" tableName="t_p1_comment" domainObjectName="Comment"-->
               <!--enableCountByExample="false" enableDeleteByExample="false"-->
               <!--enableSelectByExample="false" enableUpdateByExample="false">-->
            <!--<property name="useActualColumnNames" value="true" />-->
        <!--</table>-->

        <!--<table schema="" tableName="t_p1_link" domainObjectName="Link"-->
               <!--enableCountByExample="false" enableDeleteByExample="false"-->
               <!--enableSelectByExample="false" enableUpdateByExample="false">-->
            <!--<property name="useActualColumnNames" value="true" />-->
        <!--</table>-->

        <!--<table schema="" tableName="t_p1_systemParam" domainObjectName="SystemParam"-->
               <!--enableCountByExample="false" enableDeleteByExample="false"-->
               <!--enableSelectByExample="false" enableUpdateByExample="false">-->
            <!--<property name="useActualColumnNames" value="true" />-->
        <!--</table>-->

        <!--<table schema="" tableName="t_p1_data_dictionary" domainObjectName="DataDictionary"-->
               <!--enableCountByExample="false" enableDeleteByExample="false"-->
               <!--enableSelectByExample="false" enableUpdateByExample="false">-->
            <!--<property name="useActualColumnNames" value="true" />-->
        <!--</table>-->

        <!--<table schema="" tableName="t_p1_stu_blog" domainObjectName="StuBlog"-->
               <!--enableCountByExample="false" enableDeleteByExample="false"-->
               <!--enableSelectByExample="false" enableUpdateByExample="false">-->
            <!--<property name="useActualColumnNames" value="true" />-->
        <!--</table>-->

        <!--<table schema="" tableName="t_p1_vedio" domainObjectName="Vedio"-->
               <!--enableCountByExample="false" enableDeleteByExample="false"-->
               <!--enableSelectByExample="false" enableUpdateByExample="false">-->
            <!--<property name="useActualColumnNames" value="true" />-->
        <!--</table>-->

        <!--<table schema="" tableName="t_p1_demoSite" domainObjectName="DemoSite"-->
               <!--enableCountByExample="false" enableDeleteByExample="false"-->
               <!--enableSelectByExample="false" enableUpdateByExample="false">-->
            <!--<property name="useActualColumnNames" value="true" />-->
        <!--</table>-->

        <!--<table schema="" tableName="t_p1_stu_blog" domainObjectName="StuBlog"-->
               <!--enableCountByExample="false" enableDeleteByExample="false"-->
               <!--enableSelectByExample="false" enableUpdateByExample="false">-->
            <!--<property name="useActualColumnNames" value="true" />-->
        <!--</table>-->

        <table schema="" tableName="t_p1_employInfo" domainObjectName="EmployInfo"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">
            <property name="useActualColumnNames" value="true" />
        </table>


    </context>
</generatorConfiguration>

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/xxx?useUnicode=true&characterEncoding=UTF-8
jdbc.username=xxx
jdbc.password=xxx
jdbc.initialSize=10
jdbc.maxTotal=100
jdbc.maxIdle=50
jdbc.minIdle=10
jdbc.maxWaitMillis=-1

     配置EditConfiguations的Maven啓動方式

      命令:mybatis-generator:generate -e

注意: <1>解決@Repository標籤註解報錯問題

      1>@Repository標籤改爲@Mapper標籤
            
      添加@Mapper註解之後,這個接口在編譯時會生成相應的實現類。但請注意,這個接口中不可以定義同名的方法,因爲會生成相同的id,因此這個接口不支持重載。這樣做雖然能解決問題,但以後都要爲每個Dao層的接口添加@Mapper註解

      2> 不修改@Repository註解,在啓動類中添加@MapperScan(“xxxx”)註解,用於掃描Mapper類的包。

      掃描多個包:@MapperScan({”com.dao”,”com.pojo”})

<2> 測試類要注意的

加上註解

 @RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = 測試類名.class)

 

整合pagehelper插件

1> 引入依賴

 <dependency>
     <groupId>com.github.pagehelper</groupId>
     <artifactId>pagehelper-spring-boot-starter</artifactId>
     <version>1.2.3</version>
  </dependency>

  2> 配置application.yml

#pagehelper分頁插件配置
  pagehelper:
     helperDialect: mysql
     reasonable: true
     supportMethodsArguments: true
     params: count=countSql

分頁切面代碼

/**
 *
 * 用於所有表的分頁操作
 */
@Component
@Aspect
public class PagerAspect {

    @Around("execution(* *..*Service.*Pager(..))")
    public Object invoke(ProceedingJoinPoint args) throws Throwable{
        Object[] params = args.getArgs();
        PageBean pageBean = null;
        for (Object param : params) {
            if(param instanceof PageBean){
                pageBean = (PageBean) param;
                break;
            }
        }

        if (pageBean !=null && pageBean.isPagination())
        PageHelper.startPage(pageBean.getPage(),pageBean.getRows());

        Object proceed = args.proceed(params);

        if (pageBean !=null && pageBean.isPagination()){
            PageInfo pageInfo = new PageInfo((List)proceed);
            pageBean.setTotal(pageInfo.getTotal()+"");
        }
        return proceed;
    }
}

util


/**
 * 分頁工具類
 *
 */
public class PageBean {

	private int page = 1;// 頁碼

	private int rows = 10;// 頁大小

	private int total = 0;// 總記錄數

	private boolean pagination = true;// 是否分頁
	
//	保存上次查詢的參數
	private Map<String, String[]> paramMap;
//	保存上次查詢的url
	private String url;
	
	public void setRequest(HttpServletRequest request) {
		String page = request.getParameter("page");
		String rows = request.getParameter("limit");
		String pagination = request.getParameter("pagination");
		this.setPage(page);
		this.setRows(rows);
		this.setPagination(pagination);
		this.setUrl(request.getRequestURL().toString());
		this.setParamMap(request.getParameterMap());
	}

	public PageBean() {
		super();
	}

	public Map<String, String[]> getParamMap() {
		return paramMap;
	}

	public void setParamMap(Map<String, String[]> paramMap) {
		this.paramMap = paramMap;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}
	
	public void setPage(String page) {
		if(StringUtils.isNotBlank(page)) {
			this.page = Integer.parseInt(page);
		}
	}

	public int getRows() {
		return rows;
	}

	public void setRows(String rows) {
		if(StringUtils.isNotBlank(rows)) {
			this.rows = Integer.parseInt(rows);
		}
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public void setTotal(String total) {
		if(StringUtils.isNotBlank(total)) {
			this.total = Integer.parseInt(total);
		}
	}

	public boolean isPagination() {
		return pagination;
	}

	public void setPagination(boolean pagination) {
		this.pagination = pagination;
	}
	
	public void setPagination(String pagination) {
		if(StringUtils.isNotBlank(pagination) && "false".equals(pagination)) {
			this.pagination = Boolean.parseBoolean(pagination);
		}
	}
	
	/**
	 * 最大頁
	 * @return
	 */
	public int getMaxPage() {
		int max = this.total/this.rows;
		if(this.total % this.rows !=0) {
			max ++ ;
		}
		return max;
	}
	
	/**
	 * 下一頁
	 * @return
	 */
	public int getNextPage() {
		int nextPage = this.page + 1;
		if(nextPage > this.getMaxPage()) {
			nextPage = this.getMaxPage();
		}
		return nextPage;
	}
	
	/**
	 * 上一頁
	 * @return
	 */
	public int getPreviousPage() {
		int previousPage = this.page -1;
		if(previousPage < 1) {
			previousPage = 1;
		}
		return previousPage;
	}
		

	/**
	 * 獲得起始記錄的下標
	 * 
	 * @return
	 */
	public int getStartIndex() {
		return (this.page - 1) * this.rows;
	}

	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
	}

}

編寫一個測試方法即可

 

配置log日誌

  配置application.yml

 #顯示日誌
  logging:
     level: 
       com.zking.springboot01.mapper: debug

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章