Spring-boot
一. 第一個Spring-boot的應用
1.1 maven配置
在maven文件中加入如下的依賴:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
1.2 編寫主配置文件
spring-boot的主配置文件名字按照約定叫application.yml或者application.properties,推薦使用application.yml,文件的內容如下:
server:
port: 8080
spring:
application:
name: first-spring-boot
1.3 編寫入口程序
@SpringBootApplication
public class FirstBootApplication {
public static void main( String[] args ) {
SpringApplication.run(FirstBootApplication.class, args);
}
}
spring-boot的啓動類上必須要加上@SpringBootApplication這個註解。
1.4 編寫Controller
@RestController
@RequestMapping("first")
public class FirstController {
@RequestMapping
public Object print() {
return Arrays.asList("hello", "world");
}
}
1.5 測試
啓動主程序,然後在瀏覽器中輸入:http://localhost:8080/first
二. banner的設置
在spring-boot應用啓動的時候,會出現一個很大的“Spring”字樣,那麼我們如何修改呢?
在resources資源文件下創建一個名爲banner.txt的文件,然後在這個文件中去定義我們自己想要的內容。目前網上有很多可以定製各種字樣的網站。
三. Logback
日誌任何一個項目都必須要存在的,它可以記錄我們的很多信息 ,例如報錯信息,訪問信息等,方便我們進行系統的調試和數據的分析,那麼我們就得選擇一個好的日誌框架。我們這節主要講解Logback這個日誌框架,它的執行速度上比Log4j可以快上最高10倍以上。
使用Logback我們首先得定義名爲logback-spring.xml文件,文件的內容如下:
<?xml version="1.0" encoding="UTF-8"?>
<!-- scan: 當配置文件被修改後, 將會被重新載入。
scanPeriod: 置監測配置文件是否有修改的時間間隔,如果沒有給出時間單位,默認單位是毫秒。當scan爲true時,此屬性生效。默認的時間間隔爲1分鐘。
debug: 當此屬性設置爲true時,將打印出logback內部日誌信息,實時查看logback運行狀態。默認值爲false。 -->
<configuration scan="true" scanPeriod="60 seconds" debug="false">
<!-- 輸出到控制檯 -->
<appender name="stdout" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<!-- 配置日誌輸出到控制檯的格式 -->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} -- %-4relative %-5level %logger{32} %thread -- %msg%n</pattern>
<charset>utf-8</charset>
</encoder>
</appender>
<!-- 將日誌記錄到文件當中 -->
<appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 基於時間和大小的的滾動策略 -->
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!--日誌文件輸出的文件名, 必須包含%i, 從1開始-->
<FileNamePattern>D:/logs/logback.%d{yyyy-MM-dd}.%i.log</FileNamePattern>
<!--日誌文件保留天數-->
<MaxHistory>30</MaxHistory>
<!-- 最大20KB 超過最大值,會重新建一個文件-->
<maxFileSize>20MB</maxFileSize>
<!-- 所有的日誌加起來最大的大小 -->
<totalSizeCap>400MB</totalSizeCap>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--格式化輸出:%d表示日期,%thread表示線程名,%-5level:級別從左顯示5個字符寬度%msg:日誌消息,%n是換行符-->
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level %thread -- %msg%n</pattern>
<charset>utf-8</charset>
</encoder>
</appender>
<!-- root節點是必選節點,用來指定最基礎的日誌輸出級別,只有一個level屬性。 -->
<root level="INFO">
<!-- 標識這個appender將會添加到這個loger。 -->
<appender-ref ref="stdout"/>
<appender-ref ref="file"/>
</root>
</configuration>
%d: 日期轉換,花括號中指定日期的格式。
%-4relative: 該條日誌輸出的時間,這個時間是相對於服務器啓動到打印出這條日誌的相對時間,4表示時間佔用的寬度。
%-5level: 日誌的級別,日誌總共5個級別,分別是debug,info,warn,error,fatal,從左往右日誌級別越高,5表示日誌級別佔用的字符寬度。
%thread:該日誌所屬的線程。
%msg:日誌信息。
%logger{32}:輸出該日誌信息的類,32表示包的層級。
%n: 換行。
四. yaml語法
4.1基本語法
k:(空格)v: 表示一對鍵值對,空格是必須的。
以空格的縮進控制層級關係,空多少個格子沒有特定的要求,只要左端對齊,都是同一級的數據。
spring:
datasource:
username: root
password: 123456
4.2 值的寫法
A. 字面量:普通的值(數字,字符串,布爾值)
person:
name: zhangsan
male: false
age: 20
B. 數組或者集合(類似於java中的List、Set)
pets:`
- cat
- dog
- pig
五. thymeleaf模板引擎
Thymeleaf是面向Web和獨立環境的現代服務器端Java模板引擎,能夠處理HTML, XML, JavaScript, CSS甚至純文本。Thymeleaf的主要目標是提供一個優雅和高度可維護的創建模板的方式。爲了實現這一點,它建立在自然模板的概念上,將其邏輯注入到模板文件中,不會影響模板被用作設計原型。這改善了設計的溝通,彌合了設計和開發團隊之間的差距。Thymeleaf也從一開始就設計了Web標準 - 特別是HTML5 - 允許您創建完全驗證的模板,如果這是您需要的。下面我們就開始學習spring-boot是如何整合thymeleaf.
5.1 配置依賴
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
5.2 application.yml配置
spring:
resources:
#靜態資源的存放位置,名字也可以叫/public
static-locations: classpath:/static/
thymeleaf:
enabled: true #是否使用thymeleaf模板引擎
cache: false #是否緩存,在開發階段設置false, 生產上爲true
encoding: utf-8
mode: html
prefix: classpath:/templates/ #模板存放的位置
suffix: .html #後綴
5.3 thymeleaf的用法
A. 引入命名空間
<html xmlns:th="http://www.thymeleaf.org" lang="en">
B. 資源引入與普通鏈接
th:src="@{}"
<script type="text/javascript" th:src="@{js/jquery-1.12.4.js}"></script>
<img th:src="@{images/ly.jpg}" style="height: 230px; width: 150px;">
th:href="@{}"
<link rel="stylesheet" type="text/css" th:href="@{css/bootstrap.min.css}" />
<a th:href="@{http://www.baidu.com}">百度</a>
C. 普通取值
<span th:text="${user.name}"></span>
D. 字符串拼接
<span th:text="${'你好: ' + user.name + ', 歡迎您!'}"></span>
<span th:text="|你好: ${user.name}, 歡迎您!|"></span>
E. 鏈接取值
<a href="delete?id=${user.id}">刪除</a> <!-- 獲取不到user.id的值 --> <br>
<a th:href="@{'delete?id=' + ${user.id} + '&name=' + ${user.name}}">刪除</a> <br>
<a th:href="@{delte(id=${user.id}, name=${user.name})}">刪除</a>
F. 條件判斷
<span th:if="${user.id < 10}">hello</span>
<span th:unless="${user.id > 10}">hello</span>
G. 其他形式的條件判斷
if-then
<span th:text="${age} > 10 ? '年齡大於10歲'"></span>
if-then-else
<span th:text="${age > 20 ? '年齡大於20歲' : '年齡小於或等於20歲'}"></span>
if-else
<span th:text="${name} ?: '其他人'"></span> <!-- ${name}沒有值,直接取'其他人' -->
H. 等值判斷比較
<div th:switch="${user.name}">
<p th:case="${admin}">超級管理員</p>
<p th:case="'zhangsan'">普通用戶</p>
<p th:case="*">其他用戶</p>
</div>
I. 循環遍歷
<table border="1" width="20%">
<tr>
<th>ID</th>
<th>用戶名</th>
</tr>
<tr th:each="u,stat:${list}">
<td th:text="${u.id}"></td>
<td th:text="${u.name}"></td>
</tr>
</table>
其中u爲每次遍歷的數據,stat爲狀態,狀態總共有以下幾種方式:
狀態碼 | 描述信息 |
---|---|
first | 是否爲第一條數據 |
last | 是否爲最後一條數據 |
even | 是否爲偶數條數據 |
odd | 是否爲奇數條數據 |
index | 數據的索引 |
count | 數據是第幾條 |
size | 遍歷的數據的總量 |
current | 當前遍歷的數據 |
J. map
<p th:each="m:${mps}">
<span th:text="${m.key}"></span> ----
<span th:text="${m.value}"></span><br>
</p>
K. 模板表達式
thymeleaf提供了豐富的模板表達式,而且有很多的方法用以使用,主要包括以下模板表達式:
- #lists
- ${#lists.size() }
- ${#lists.isEmpty()}
- ${#lists.contains()}
- #maps
- ${#maps.size()}
- ${#maps.isEmpty()}
- ${#maps.containsKey()}
- ${#maps.containsValue()}
3)#strings
-
${#strings.isEmpty(name)}
-
${#strings.contains(name,‘ez’)}
-
${#strings.containsIgnoreCase(name,‘ez’)}
-
${#strings.startsWith(name,‘Don’)}
-
${#strings.endsWith(name,endingFragment)}
-
${#strings.indexOf(name,frag)}
-
${#strings.substring(name,3,5)}
-
${#strings.replace(name,‘las’,‘ler’)}
-
${#strings.listSplit(namesStr,’,’)}
-
${#strings.trim(str)}
-
${#strings.equals(str)}
-
${#strings.equalsIgnoreCase(str)}
-
${#strings.prepend(str,prefix)}
-
${#strings.append(str,suffix)}
-
${#strings.toUpperCase(name)}
-
${#strings.toLowerCase(name)}
- #dates
- ${#dates.format()}
六. spring-boot與mybatis的整合
6.1 配置依賴
<!-- alibaba的druid數據源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.17</version>
</dependency>
<!-- mybatis代碼自動生成 -->
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
<!-- mybatis分頁支持 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.12</version>
</dependency>
<!-- tk.mybatis對mybatis做了二次封裝 -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>4.1.5</version>
</dependency>
<!-- tk.mybatis與spring boot整合 -->
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper-spring-boot-starter</artifactId>
<version>2.1.5</version>
</dependency>
6.2 代碼自動生成配置
6.2.1 插件配置
<!-- mybatis代碼自動生成 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.16</version>
</dependency>
</dependencies>
<configuration>
<!-- 配置文件的名字 -->
<configurationFile>src/main/resources/mybatis-generator-config.xml</configurationFile>
<overwrite>true</overwrite>
</configuration>
</plugin>
6.2.1 配置文件編寫
jdbc.properties,該文件與application.yml並不同,它僅僅是用於mybatis生成代碼用。
mysql.url=jdbc:mysql://localhost:3306/qf?useSSL=false&serverTimezone=UTC
mysql.driver=com.mysql.cj.jdbc.Driver
mysql.username=root
mysql.password=123456
mybatis-generator-config.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"/>
<!--
context:生成一組對象的環境
id:必選,上下文id,用於在生成錯誤時提示
defaultModelType=flat 就是將所有的屬性都生成在一個類中。
targetRuntime:
1,MyBatis3:默認的值,生成基於MyBatis3.x以上版本的內容,包括XXXBySample;
2,MyBatis3Simple:類似MyBatis3,只是不生成XXXBySample;
-->
<context id="Mysql" targetRuntime="MyBatis3Simple" defaultModelType="flat">
<!-- 自動識別數據庫關鍵字,默認false,如果設置爲true,根據SqlReservedWords中定義的關鍵字列表;
一般保留默認值,遇到數據庫關鍵字(Java關鍵字),使用columnOverride覆蓋
-->
<property name="autoDelimitKeywords" value="true" />
<!-- beginningDelimiter和endingDelimiter:指明數據庫的用於標記數據庫對象名的符號,比如ORACLE就是雙引號,MYSQL默認是`反引號; -->
<property name="beginningDelimiter" value="`" />
<property name="endingDelimiter" value="`" />
<property name="javaFileEncoding" value="utf-8" />
<!-- 格式化java代碼 -->
<property name="javaFormatter" value="org.mybatis.generator.api.dom.DefaultJavaFormatter"/>
<!-- 格式化XML代碼 -->
<property name="xmlFormatter" value="org.mybatis.generator.api.dom.DefaultXmlFormatter"/>
<!-- 註釋 -->
<commentGenerator >
<property name="suppressAllComments" value="false"/><!-- 是否取消註釋 -->
<property name="suppressDate" value="false" /> <!-- 是否生成註釋代時間戳-->
</commentGenerator>
<!--數據庫鏈接地址賬號密碼-->
<jdbcConnection driverClass="${mysql.driver}"
connectionURL="${mysql.url}"
userId="${mysql.username}"
password="${mysql.password}">
</jdbcConnection>
<!-- 類型轉換 -->
<javaTypeResolver>
<!--
true:使用BigDecimal對應DECIMAL和 NUMERIC數據類型
false:默認,
scale>0;length>18:使用BigDecimal;
scale=0;length[10,18]:使用Long;
scale=0;length[5,9]:使用Integer;
scale=0;length<5:使用Short;
-->
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- java模型創建器,是必須要的元素
負責:1,key類(見context的defaultModelType);2,java類;3,查詢類
targetPackage:生成的類要放的包,真實的包受enableSubPackages屬性控制;
targetProject:目標項目,指定一個存在的目錄下,生成的內容會放到指定目錄中,如果目錄不存在,MBG不會自動建目錄
-->
<javaModelGenerator targetPackage="com.qf.pojo" targetProject="src/main/java">
<!-- for MyBatis3/MyBatis3Simple
自動爲每一個生成的類創建一個構造方法,構造方法包含了所有的field;而不是使用setter;
-->
<property name="constructorBased" value="true"/>
<!-- 在targetPackage的基礎上,根據數據庫的schema再生成一層package,最終生成的類放在這個package下,默認爲false -->
<property name="enableSubPackages" value="false"/>
<!-- 設置是否在getter方法中,對String類型字段調用trim()方法 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成的mapper文件存放的位置 -->
<sqlMapGenerator targetPackage="mybatis.mapper" targetProject="src/main/resources">
<!-- 在targetPackage的基礎上,根據數據庫的schema再生成一層package,最終生成的類放在這個package下,默認爲false -->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- 對於mybatis來說,即生成Mapper接口,注意,如果沒有配置該元素,那麼默認不會生成Mapper接口
targetPackage/targetProject:同javaModelGenerator
type:選擇怎麼生成mapper接口(在MyBatis3/MyBatis3Simple下):
1,ANNOTATEDMAPPER:會生成使用Mapper接口+Annotation的方式創建(SQL生成在annotation中),不會生成對應的XML;
2,MIXEDMAPPER:使用混合配置,會生成Mapper接口,並適當添加合適的Annotation,但是XML會生成在XML中;
3,XMLMAPPER:會生成Mapper接口,接口完全依賴XML;
注意,如果context是MyBatis3Simple:只支持ANNOTATEDMAPPER和XMLMAPPER
-->
<javaClientGenerator targetPackage="com.qf.dao" type="XMLMAPPER" targetProject="src/main/java">
<!-- 在targetPackage的基礎上,根據數據庫的schema再生成一層package,最終生成的類放在這個package下,默認爲false -->
<property name="enableSubPackages" value="false"/>
<!-- 可以爲所有生成的接口添加一個父接口,但是MBG只負責生成,不負責檢查
<property name="rootInterface" value=""/>
-->
</javaClientGenerator>
<!-- 選擇一個table來生成相關文件,可以有一個或多個table,必須要有table元素
選擇的table會生成一下文件:
1,SQL map文件
2,生成一個主鍵類;
3,除了BLOB和主鍵的其他字段的類;
4,包含BLOB的類;
5,一個用戶生成動態查詢的條件類(selectByExample, deleteByExample),可選;
6,Mapper接口(可選)
tableName(必要):要生成對象的表名;
注意:大小寫敏感問題。正常情況下,MBG會自動的去識別數據庫標識符的大小寫敏感度,在一般情況下,MBG會
根據設置的schema,catalog或tablename去查詢數據表,按照下面的流程:
1,如果schema,catalog或tablename中有空格,那麼設置的是什麼格式,就精確的使用指定的大小寫格式去查詢;
2,否則,如果數據庫的標識符使用大寫的,那麼MBG自動把表名變成大寫再查找;
3,否則,如果數據庫的標識符使用小寫的,那麼MBG自動把表名變成小寫再查找;
4,否則,使用指定的大小寫格式查詢;
另外的,如果在創建表的時候,使用的""把數據庫對象規定大小寫,就算數據庫標識符是使用的大寫,在這種情況下也會使用給定的大小寫來創建表名;
這個時候,請設置delimitIdentifiers="true"即可保留大小寫格式;
可選:
1,domainObjectName:生成的domain類的名字,如果不設置,直接使用表名作爲domain類的名字;可以設置爲somepck.domainName,那麼會自動把domainName類再放到somepck包裏面;
2,enableInsert(默認true):指定是否生成insert語句;
3,enableSelectByPrimaryKey(默認true):指定是否生成按照主鍵查詢對象的語句(就是getById或get);
4,enableSelectByExample(默認true):MyBatis3Simple爲false,指定是否生成動態查詢語句;
5,enableUpdateByPrimaryKey(默認true):指定是否生成按照主鍵修改對象的語句(即update);
6,enableDeleteByPrimaryKey(默認true):指定是否生成按照主鍵刪除對象的語句(即delete);
7,enableDeleteByExample(默認true):MyBatis3Simple爲false,指定是否生成動態刪除語句;
8,enableCountByExample(默認true):MyBatis3Simple爲false,指定是否生成動態查詢總條數語句(用於分頁的總條數查詢);
9,enableUpdateByExample(默認true):MyBatis3Simple爲false,指定是否生成動態修改語句(只修改對象中不爲空的屬性);
-->
<table schema="qf" tableName="user" domainObjectName="MyUser" enableInsert="true">
<!-- 注意,該屬性只針對MyBatis3Simple有用;
如果選擇的runtime是MyBatis3Simple,那麼會生成一個SelectAll方法,如果指定了selectAllOrderByClause,那麼會在該SQL中添加指定的這個order條件;
-->
<property name="selectAllOrderByClause" value="id desc"/>
<!-- 如果設置爲true,生成的model類會直接使用column本身的名字,而不會再使用駝峯命名方法,比如BORN_DATE,生成的屬性名字就是BORN_DATE,而不會是bornDate -->
<property name="useActualColumnNames" value="true"/>
<!-- generatedKey用於生成生成主鍵的方法,
如果設置了該元素,MBG會在生成的<insert>元素中生成一條正確的<selectKey>元素,該元素可選
column:主鍵的列名;
sqlStatement:要生成的selectKey語句,有以下可選項:
Cloudscape:相當於selectKey的SQL爲: VALUES IDENTITY_VAL_LOCAL()
DB2 :相當於selectKey的SQL爲: VALUES IDENTITY_VAL_LOCAL()
DB2_MF :相當於selectKey的SQL爲:SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1
Derby :相當於selectKey的SQL爲:VALUES IDENTITY_VAL_LOCAL()
HSQLDB :相當於selectKey的SQL爲:CALL IDENTITY()
Informix :相當於selectKey的SQL爲:select dbinfo('sqlca.sqlerrd1') from systables where tabid=1
MySql :相當於selectKey的SQL爲:SELECT LAST_INSERT_ID()
SqlServer :相當於selectKey的SQL爲:SELECT SCOPE_IDENTITY()
SYBASE :相當於selectKey的SQL爲:SELECT @@IDENTITY
JDBC :相當於在生成的insert元素上添加useGeneratedKeys="true"和keyProperty屬性
<generatedKey column="id" sqlStatement="MySql" identity="true" />
-->
<generatedKey column="id" sqlStatement="MySql" identity="true" />
<!-- 用來修改表中某個列的屬性,MBG會使用修改後的列來生成domain的屬性;
column:要重新設置的列名;
注意,一個table元素中可以有多個columnOverride元素哈~
使用property屬性來指定列要生成的屬性名稱
-->
<!--
<columnOverride column="username">
<property name="property" value="userName"/>
</columnOverride>
-->
<!-- ignoreColumn設置一個MGB忽略的列,如果設置了該列,那麼在生成的domain中,生成的SQL中,都不會有該列出現
column:指定要忽略的列的名字;
delimitedColumnName:參考table元素的delimitAllColumns配置,默認爲false
注意,一個table元素中可以有多個ignoreColumn元素
<ignoreColumn column="deptId" delimitedColumnName=""/>
-->
</table>
</context>
</generatorConfiguration>
6.2.3 執行生成代碼
6.3 分頁插件的使用
6.3.1 application.yml文件的配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/qf?useSSL=false&serverTimezone=UTC
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
druid:
initial-size: 5
max-active: 8
min-idle: 2
validation-query: 'select 1'
test-on-borrow: false
test-on-return: false
test-while-idle: true
# psCache, 緩存preparedStatement, 對支持遊標的數據庫性能有巨大的提升,oracle開啓,mysql建議關閉
pool-prepared-statements: false
# psCache開啓的時候有效
max-open-prepared-statements: 100
# 一個連接在被驅逐出連接池的時候,在連接池中最小的空閒時間,單位爲毫秒
min-evictable-idle-time-millis: 30000
# 距離上次釋放空閒連接的時間間隔
time-between-eviction-runs-millis: 30000
pagehelper:
dialect: mysql #配置數據庫的方言
# 分頁合理化參數,默認值爲false。當該參數設置爲 true 時,pageNum<=0 時會查詢第一頁, pageNum>pages(超過總數時),會查詢最後一頁
reasonable: true
# 支持通過 Mapper 接口參數來傳遞分頁參數
support-methods-arguments: true
mybatis:
mapper-locations: classpath:/mybatis.mapper/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
6.3.2 通用接口的編寫
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.common.MySqlMapper;
public interface MyMapper<T> extends Mapper<T>, MySqlMapper<T> {
}
6.3.3 接口的編寫
import com.github.pagehelper.Page;
import com.qf.pojo.MyUser;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface MyUserMapper extends MyMapper<MyUser> {
List<MyUser> selectAll();
Page<MyUser> selectPage();
}
6.3.4 服務層編寫
import com.github.pagehelper.PageHelper;
import com.qf.dao.MyUserMapper;
import com.qf.pojo.MyUser;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserService {
@Resource
private MyUserMapper myUserMapper;
public List<MyUser> getList() {
PageHelper.startPage(1, 2);
Example example = new Example(MyUser.class);
List<MyUser> list = myUserMapper.selectByExample(example);
return list;
}
}
參考地址:
mybatis官網參考地址:http://www.mybatis.org/spring-boot-starter/
mybatis生成代碼官網參考地址:http://www.mybatis.org/generator/
##### 6.3.4 服務層編寫
import com.github.pagehelper.PageHelper;
import com.qf.dao.MyUserMapper;
import com.qf.pojo.MyUser;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;
import javax.annotation.Resource;
import java.util.List;
@Service
public class UserService {
@Resource
private MyUserMapper myUserMapper;
public List<MyUser> getList() {
PageHelper.startPage(1, 2);
Example example = new Example(MyUser.class);
List<MyUser> list = myUserMapper.selectByExample(example);
return list;
}
}
參考地址:
**mybatis官網參考地址:<http://www.mybatis.org/spring-boot-starter/>**
**mybatis生成代碼官網參考地址:<http://www.mybatis.org/generator/>**
**配置文件編寫參考地址:<https://www.jianshu.com/p/e09d2370b796>**