MyBatis快速入門
先說說緣由為啥今天才來學習和總結MyBatis。。
我自己學Springboot剛入門的時候,用SptingBoot+JdbcTemplate+thmysef搭建了一個bug管理平臺
後來自己用自己的介面,測試DB連線數對效能的影響,TPS會特別受到程式中連線池的配置影響
後來DB中就湧現了很多資料,我的bug管理平臺,有一個介面是列出所有的bug,這個頁面就會特別特別地慢,於是想到分頁。
在網上查詢分頁資訊的時候,發現大多數都是針對MyBatis的,用JdbcTemplate的查詢,將沒有現成的分頁外掛,需要自己改寫JdbcTemplate中的一些方法,要新增頁碼和每頁的條數
每天依舊,工作依舊。
忽然一日得閒,又開始自學SpringBoot,於是根據教程先用springboot+MyBatis+MyBatis自動生成了Mapper和實體類。
難道MyBatis必須在SpringBoot框架中? 忽然冒出這樣的疑問之後,就開始搜尋MyBatis的歷史,也開始最簡單的學習。
mybatis是什麼?最初開發出來做什麼的?
MyBatis 本是apache的一個開源專案iBatis, 2010年這個專案由apache software foundation 遷移到了google code,並且改名為MyBatis 。
2013年11月遷移到Github。
iBATIS一詞來源於“internet”和“abatis”的組合,是一個基於Java的持久層框架。
iBATIS提供的持久層框架包括SQL Maps和Data Access Objects(DAOs)
http://blog.mybatis.org/ mybatis官方網站 --- 需要FQ
http://www.mybatis.cn/ MyBatis的中文官網
https://github.com/mybatis/mybatis-3/releases
下載第一個zip格式的,解壓後如下圖,其中有個pdf文件,可以參考用來配置mapper以及配置config檔案。 License和Notice只是一些證書說明等,可以忽略。lib目錄下是一些常搭配的jar包。
mybatis-xx.xx.x.jar 可以放置到自己的專案源中。用了maven的話,可以自己去找maven的路徑。
mybatis是怎麼用的呢?
不管是何種程式,持久化的資料都是重中之重。不可能讓前段使用者直接去操作資料庫吧,這樣都不安全,而且也不是任何一個人都會的。
所以要用程式編寫頁面,編寫後臺介面,讓mybaits操作物件,就像操作資料庫這麼簡單。
user表, user物件,一一對應
想檢視,想更新,想新增,直接操作物件,就能存入持久化資料DB中
use test select * from user create table user( id INT NOT NULL auto_increment primary key, name VARCHAR(20), age int, phone varchar(20), password varchar(20) )ENGINE=InnoDB AUTO_INCREMENT=300; insert user(name,age,phone,password) values ("王族 ",33,"18962811111","12345")
以上是建立了user表,接下來建立User物件
public class User { private Integer id; private String name; private String phone; private String password; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public User(){ } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", phone='" + phone + '\'' + ", password='" + password + '\'' + ", age=" + age + '}'; } }
表和物件都有了,現在就是mybatis的作用了,首先要進行配置config.xml,然後配置對映檔案UserMapper.xml.這些在剛下載的pdf中都有介紹,有例子。
上面是專案的目錄結構,我建立的有點隨意,下面l兩個分別是config.xml 和UserMapper.xml對映檔案
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/test"/> <property name="username" value="root"/> <property name="password" value="root"/> </dataSource> </environment> </environments> <mappers> <mapper resource="UserMapper.xml"/> </mappers> </configuration>
<?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="useraaa"> <select id="selectById" resultType="com.test.mybatis.entity.User"> select * from user where id = #{id} </select> <select id="selectAll" resultType="com.test.mybatis.entity.User"> select * from user </select> </mapper>
下面是如何讀取配置檔案config.xml,如何將UserMapper中的查詢語句打印出表中的資訊
用了testNG來測試,具體測試內容如下
import com.test.mybatis.entity.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.testng.annotations.Test; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.List; public class TestMyBatis { @Test(description = "通過InputStream讀取配置config檔案") public void TestInputStream() throws IOException { String resource = "config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sessionFactory= new SqlSessionFactoryBuilder().build(inputStream); SqlSession session =sessionFactory.openSession(); String statement = "useraaa.selectById"; User user = session.selectOne(statement,300); System.out.println(user); session.close(); } @Test(description = "通過Reader讀取配置config檔案") public void Reader() throws IOException { Reader reader =Resources.getResourceAsReader("config.xml"); SqlSessionFactory sessionFactory= new SqlSessionFactoryBuilder().build(reader); SqlSession session =sessionFactory.openSession(); String statement = "useraaa.selectById"; User user = session.selectOne(statement,300); System.out.println(user); session.close(); } @Test(description = "讀取所有的物件") public void selectAll() throws IOException { Reader reader =Resources.getResourceAsReader("config.xml"); SqlSessionFactory sessionFactory= new SqlSessionFactoryBuilder().build(reader); SqlSession session =sessionFactory.openSession(); String statement = "useraaa.selectAll"; List<User> user = session.selectList(statement); System.out.println(user); session.close(); } }
pom.xml
<?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>mybatis01</groupId> <artifactId>mybatis</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.0</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.14</version> </dependency> <!-- https://mvnrepository.com/artifact/org.testng/testng --> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>6.14.3</version> <scope>test</scope> </dependency> </dependencies> </project>
mybatis使用中要注意的地方?
1. config.xml 和 Mapper.xml 中的頭部分要複製正確,是不一樣的,config中是configration,後者是Mapper
2. config.xml中資料的連線url,驅動,使用者名稱和密碼要全部填寫正確
3.UserMapper.xml中的namespace 要用到,之後讀取的是namespace.select的id的值,如下