SpringBoot2.0(三) 整合MyBatis
一、建立專案
使用idea建立springboot專案,可以直接新增mybatis和mysql資料庫的相關依賴,
只需要再建立專案的時候多勾幾個勾就可以了
(如果使用的不是idea開發工具,可以按照你熟悉的方式建立maven專案,新增下邊的pom.xml檔案中的內容即可)
1.1 選擇建立spring專案
1.2 勾選springboot的web、mybatis、mysql支援
沒有截圖的步驟按照正常專案的建立方式即可
下邊是專案建立成功之後生成的pom.xml檔案,可以在<dependencies>依賴中發現包含mybatis和mysql的依賴。
<?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> <groupId>com.peng</groupId> <artifactId>springboot_mybatis</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>springboot_mybatis</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.4.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <!--web--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--test--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!--mybatis--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.2</version> </dependency> <!--mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
二、使用MyBatis完成CRUD操作
下邊是專案最終的目錄結構
1.1 建表
CREATE TABLE student
(
id INT(10) AUTO_INCREMENT PRIMARY KEY,
sname VARCHAR(50) NOT NULL,
sage INT(10) NULL
);
1.2 建立實體類
public class Student { private int id; private String sname; private int sage; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public int getSage() { return sage; } public void setSage(int sage) { this.sage = sage; } @Override public String toString() { return "Student{" + "id=" + id + ", sname='" + sname + '\'' + ", sage=" + sage + '}'; } }
1.3 建立StudentDAO介面
public interface StudentDAO {
public List<Student> selectAll();
public int insert(Student stu);
public int delete(int id);
public int update(Student stu);
}
1.4建立StudentMapper.xml檔案
在resources下建立一個資料夾叫做mappers,該資料夾用來儲存mybatis的mapper檔案
<?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"> <!--nnamespace和介面全類名保持一致--> <mapper namespace="com.peng.springboot_mybatis.dao.StudentDAO"> <!--id和介面中方法名保持一致--> <select id="selectAll" resultType="com.peng.springboot_mybatis.entity.Student"> select * from student </select> <delete id="delete"> delete from student where id = #{id} </delete> <update id="update"> update student set sname = #{sname} ,sage = #{sage} where id = #{id} </update> <insert id="insert"> insert into student(sname,sage) VALUES (#{sname},#{sage}) </insert> </mapper>
1.5 修改application.properties檔案
#mysql資料庫連線資訊
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
#mybatis配置資訊
#mapper檔案的存放路徑
mybatis.mapper-locations=classpath:mappers/*.xml
1.6在SpringBoot的啟動類中,配置掃描器
@MapperScan("com.peng.springboot_mybatis.dao")的作用:可以對指定包下的mapper介面進行掃描
如果不配置,需要在每一個介面上邊配置@Mapper註解
@MapperScan({"xxx","yyy"}) 支援對多個包下進行掃描,也支援*號萬用字元
@SpringBootApplication
@MapperScan("com.peng.springboot_mybatis.dao")
public class SpringbootMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisApplication.class, args);
}
}
1.7編寫測試類,對CRUD方法進行測試
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootMybatisApplicationTests {
@Autowired
private StudentDAO dao; //使用idea此處會報錯,但是不影響使用
@Test
public void test1() { //測試查詢方法
List<Student> list = dao.selectAll();
for (Student student : list) {
System.out.println(student);
}
}
@Test
public void test2(){ //測試新增方法
Student stu = new Student();
stu.setSname("haha");
stu.setSage(20);
int i = dao.insert(stu);
System.out.println(i);
}
@Test
public void test3(){ //測試修改方法
Student stu = new Student();
stu.setId(6);
stu.setSname("haha");
stu.setSage(21);
int i = dao.update(stu);
System.out.println(i);
}
@Test
public void test4(){ //測試刪除方法
int i = dao.delete(2);
System.out.println(i);
}
}
-------------------------到此SpringBoot整合mybatis就結束了-----------------------------------------------------
------------------------ 下邊會對mybatis的使用進行優化-----------------------------------------------------------
配置列印SQL語句、整合pagehelper分頁外掛、使用阿里的druid資料庫連線池
三、列印SQL語句
作用:通過列印sql語句,方便檢視我們執行的SQL語句
在application.properties檔案中增加一行配置 ,記得將com.peng.springboot_mybatis.dao修改為你的package路徑
logging.level.com.peng.springboot_mybatis.dao=debug
四、整合 PageHelper
作用:PageHelper是github上的一個開源專案,可以簡化mybatis的分頁開發。如果你使用過mybatis就知道這是一個需要自己寫sql語句的半自動化orm框架,如果需要完成分頁功能,就會稍顯麻煩,使用pageHelper可以簡化分頁開發。
1.修改pom.xml檔案,增加pageHelper的依賴
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
2.編寫一個查詢全部的方法 (然後就沒了 ), 那麼下邊我們就趕緊測試一下吧
3.測試分頁的使用,在測試類中增加一個新的測試方法
PageHelper是引入的jar中的一個類,不需要自己寫,直接使用即可。
startPage方法的兩個引數分別代表pageNum(訪問第幾頁)/pageSize(每頁顯示多少條資料)
在呼叫查詢全部的方法之前先執行startPage方法,PageHelper會對接下來執行的第一個SQL語句進行物理分頁(底層使用是攔截器)
list的實際型別是Page,可以通過輸出 list.getClass()的方式檢視,所以我們可以將list物件強轉成Page,然後呼叫getTotal方法獲取總條數
@Test
public void test5(){
PageHelper.startPage(1,5); //訪問第1頁,每頁顯示5條
List<Student> list = dao.selectAll();
for (Student s : list) {
System.out.println(s);
}
long count = ((Page) list).getTotal(); //獲取總條數
System.out.println(count);
}
可以通過控制檯列印sql語句發現,實際並沒有執行查詢全部的sql語句,而是輸出了帶有limit的分頁查詢語句,並且可以看到輸出了查詢總條數的sql語句,這樣我們呼叫getTotal()方法獲取總條數也就不奇怪了.
下邊是pagehelper在github上的網址,希望深入學習的可以通過下邊的網址進一步學習
五、整合阿里的druid
1. 修改pom.xml檔案
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
2.修改application.properties ,增加spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=123456
通過上邊的配置,我們再次查詢之前寫好的查詢方法,可以在控制檯發現已經使用了druid連線池