最近接觸的項目中使用了Mybatis框架,覺得 Mybatis使用起來非常方便,決定從基礎開始學習Mybatis。我準備的環境如下:
-
JDK1.5
-
Mybatis 3.3.0版本
-
MySQL數據庫
-
Eclipse Neon.3 Release (4.6.3)
- Apache Maven 構建工具
一.創建Maven項目
首先通過Eclipse創建一個Maven Simple Project,通過配置其pom.xml添加我們所需要的jar包,在這裏我添加了Log4j,JUnit和MySQL驅動等依賴。
<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>tk.mybatis</groupId>
<artifactId>sample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.12</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
二.配置Mybatis
在這裏我通過xml形式對Mybatis進行配置,在src/main/resources下創建mybatis-config.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>
<settings>
<setting name="logImpl" value="LOG4J" />
</settings>
<typeAliases>
<package name="tk.mybatis.sample.model" />
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="" value=""/>
</transactionManager>
<dataSource type="UNPOOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="tk/mybatis/sample/mapper/CountryMapper.xml" />
</mappers>
</configuration>
-
<settings>中logImpl屬性指定使用LOG4J輸出日誌
-
<typeAliases>下配置包的別名,配置後,在使用類的時候不需要寫包名
-
<environments>配置了數據庫連接的信息
-
<mappers>配置了Mybatis的SQL語句和映射配置文件
三.創建實體類和Mapper.xml文件
在Mybatis中,一個表一般對應一個實體類,用於進行增刪改查等操作。這裏我在數據庫中建的表結構如下
根據表結構,在src/main/java下創建包tk.mybatis.sample.model,在該包下創建實體類Country如下
package tk.mybatis.sample.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/sample/mapper目錄,在該目錄下創建CountryMapper.xml文件如下:
<?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="tk.mybatis.sample.mapper.CountryMapper">
<select id="selectAll" resultType="Country">
select id,countryname,countrycode from country
</select>
</mapper>
在<select>元素表示定義的select查詢,其中id屬性爲當前select查詢的唯一id,resultType定義當前查詢的返回值類型(在這裏返回的是Country實體類),中間部分則爲該select的SQL語句。
四.配置Log4j查看Mybatis操作數據庫的過程
在src/main/resources中添加log4j.properties配置文件如下:
#global property
log4j.rootLogger=ERROR, stdout
#MyBatis log property
log4j.logger.tk.mybatis.sample.mapper=TRACE
#console out property
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
五.編寫測試代碼
在src/test/java中創建tk.mybatis.sample.mapper包,在該包下創建CountryMapperTest測試類如下:
package tk.mybatis.sample.mapper;
import java.io.IOException;
import java.io.Reader;
import java.util.List;
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.junit.BeforeClass;
import org.junit.Test;
import tk.mybatis.sample.model.Country;
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
sqlSession.close();
}
}
private void printCountryList(List<Country> countryList) {
// TODO Auto-generated method stub
for(Country country : countryList){
System.out.printf("%-4d%-4s%-4s\n",country.getId()
,country.getCountryname(),country.getCountrycode());
}
}
}
首先通過Resources工具類將mybatis-config.xml配置文件讀入Reader。
再通過SqlSessionFactoryBuilder使用Reader創建SqlSessionFactory工廠對象。
使用時通過工廠對象獲取一個SqlSession,通過其selectList方法找到CountryMapper.xml中id爲selectAll的方法並執行查詢。
Mybatis使用JDBC執行SQL,獲得查詢結果集,根據返回值類型將結果映射到Country類型的集合中。
在結束時需要關閉SqlSession,否則會因爲連接未關閉導致數據庫連接數過多造成崩潰。
六.結果展示及項目結構
項目測試成功後,會輸出如下內容:
整個項目結構如下所示: