## 1.1 MyBatis簡介
**有各種資源下載的網址**
MyBatis官方GitHub地址為https://github.com/mybatis。
· mybatis-3(https://github.com/mybatis/mybatis-3):MyBatis 源碼,也是本書中主要講解和使用的內容。
· generator(https://github.com/mybatis/generator):代碼生成器,可以生成一些常見的基本方法,提高工作效率。
· ehcache-cache(https://github.com/mybatis/ehcache-cache):默認集成Ehcache的緩存實現。
· redis-cache(https://github.com/mybatis/redis-cache):默認集成Redis的緩存實現。
· spring(https://github.com/mybatis/spring):方便和Spring集成的工具類。
· mybatis-spring-boot(https://github.com/mybatis/mybatis-spring-boot):方便和Spring Boot集成的工具類。
## 1.2 創建Maven項目
### 1.2索引
**1. 創建maven項目
2. 在pom.xml中添加編碼方式配置信息
3. 在pom.xml中添加編譯源碼的jdk版本
4. 在pom.xml中添加Log4j、JUnit和MySql和mybatis的依賴jar包
5. 在項目上單擊鼠標右鍵,在【Maven】中選擇【Update Project...],下載項目需要的jar包
6. 通過http://search.maven.org/或http://mvnrepository.com/(推薦)來查找依賴jar包。**
###### 疑問:
*1.關于maven更詳細的使用??*
## 1.3 簡單配置讓MyBatis
### 1.3.2 配置MyBatis
在src/main/resources下面創建mybatis-config.xml配置文件
```
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>
<typeAliases>
<!-- 配置了 tk.mybatis.simple.model包,這樣配置后,在使用類的時候不需要寫包名的部分-->
<package name="tk.mybatis.simple.model"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="" value=""/>
</transactionManager>
<dataSource type="UNPOOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<!--使用jdbc 8.0版本-->
<property name="url" value="jdbc:mysql://localhost:3306/lian?serverTimezone=GMT"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="tk/mybatis/simple/mapper/CountryMapper.xml"/>
</mappers>
</configuration>
```
<settings>中的logImpl屬性配置指定使用LOG4J輸出日志。
<typeAliases>
<package name="tk.mybatis.simple.model"/>
</typeAliases>
這樣配置后,在使用該包下的類時,只寫類名就可以。
<environments>環境配置中主要配置了數據庫連接,數據庫的 url 為jdbc:mysql://localhost:3306/lian?serverTimezone=GMT,使用的是本機 MySQL 中的 mybatis數據庫,后面的username和password分別是數據庫的用戶名和密碼。
<mappers>中配置了一個包含完整類路徑的CountryMapper.xml,這是一個MyBatis的SQL語句和映射配置文件。
### 1.3.3 創建實體類和Mapper.xml文件
在src/main/java下創建一個基礎的包tk.mybatis.simple.model包。
在model包下創建實體類Country。
```
package tk.mybatis.simple.model;
public class Country {
private Long id;
private String countryname;
private String countrycode;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getCountryname() {
return countryname;
}
public void setCountryname(String countryname) {
this.countryname = countryname;
}
public String getCountrycode() {
return countrycode;
}
public void setCountrycode(String countrycode) {
this.countrycode = countrycode;
}
}
```
在 src/main/resources 下面創建 tk/mybatis/simple/mapper 目錄,再在該目錄下面創建CountryMapper.xml文件。
```
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<!-- 通過namespace綁定mapper接口-->
<mapper namespace="tk.mybatis.simple.mapper.CountryMapper">
<select id="selectAll" resultType="Country">
select id,countryname,countrycode from country
</select>
</mapper>
```
* mapper標簽中的 namespace 屬性值是mapper.xml對應的mapper.java的全限定名。
### 1.3.4 配置Log4j以便查看MyBatis操作數據庫的過程
```
#全局配置
log4j.rootLogger=ERROR, stdout
#MyBatis日志配置
log4j.logger.tk.mybatis.simple.mapper=TRACE
#控制臺輸出配置
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
```
* 操作數據庫的sql語句在mapper.xml中
* log4j.logger.tk.mybatis.simple.mapper=TRACE,輸出resource/tk.mybatis.simple.mapper包下的xml操作數據庫的詳細信息。
### 1.3.5 編寫測試代碼讓MyBatis跑起來
```
public class CountryMapperTest {?
?????private static SqlSessionFactory sqlSessionFactory;
?????@BeforeClass
?????public static void init(){
???????????try {
??????????? Reader reader =
Resources.getResourceAsReader("mybatis-config.xml");
??????????? sqlSessionFactory = new
SqlSessionFactoryBuilder().build(reader);
??????????? reader.close();
??????? } catch (IOException ignore) {
??????? ????ignore.printStackTrace();
??????? }
?????}
?????
?????@Test
?????public void testSelectAll(){
???????????SqlSession sqlSession =
sqlSessionFactory.openSession();
???????????try {
????????????????List<Country> countryList =
sqlSession.selectList("selectAll");
????????????????printCountryList(countryList);
???????????} finally {
????????????????sqlSession.close();
???????????}
?????}
?????private void printCountryList(List<Country> countryList){
???????????for(Country country : countryList){
????????????????System.out.printf("%-4d%4s%4s\n",country.getId(),
country.getCountryname(), country.getCountrycode());
???????????}
?????}
}
```
**1** 通過Resources工具類將mybatis-config.xml配置文件讀入Reader。
**2** 再通過SqlSessionFactoryBuilder建造類使用Reader創建SqlSessionFactory工廠對象。在創建SqlSessionFactory對象的過程中,首先解析mybatis-config.xml配置文件,讀取配置文件中的mappers配置后會讀取全部的Mapper.xml進行具體方法的解析,在這些解析完成后,SqlSessionFactory就包含了所有的屬性配置和執行SQL的信息。· 使用時通過SqlSessionFactory工廠對象獲取一個SqlSession。
**3** 通過SqlSession的selectList方法查找到CountryMapper.xml中id="selectAll"的方法,執行SQL查詢。
**4** MyBatis底層使用JDBC執行SQL,獲得查詢結果集ResultSet后,根據resultType的配置將結果映射為Country類型的集合,返回查詢結果。
**5** 這樣就得到了最后的查詢結果countryList,簡單將結果輸出到控制臺。· 最后一定不要忘記關閉 SqlSession,否則會因為連接沒有關閉導致數據庫連接數過多,造成系統崩潰。