最近接触的项目中使用了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,否则会因为连接未关闭导致数据库连接数过多造成崩溃。
六.结果展示及项目结构
项目测试成功后,会输出如下内容:
整个项目结构如下所示: