在学习一个框架的时候,可能需要先做一个小案例先跑起来,然后再慢慢去研究它的实现。
现在我就来总结一下如何先让Mybatis跑起来。
首先:
我们需要一个项目,这里我使用的时Maven项目,因为导包容易,易于管理。
第一步:在idea中创建一个maven项目,因为只是研究MyBatis的使用,java项目或者web项目都没关系
第二步:在maven的pom文件中开始加入依赖
<?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.zale</groupId>
<artifactId>mybaits</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<!--mybatis项目的核心包-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<!--mysql的连接驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<!--junit测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<!--三个打印Log的依赖-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!--测试依赖-->
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.8</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.8</version>
<scope>compile</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
第三步:加入完必要的依赖之后,就开始准备数据库的环境,我这里使用的是mysql数据库。
create database mybatis default character set utf8 collate utf8_general_ci;
use mybatis;
create table `country`(
`id` int primary key auto_increment,
`countryname` varchar(40),
`countrycode` varchar(40)
);
insert `country` values (null,'中国','CN'),(null,'美国','US'),(null,'俄罗斯','RU'),(null,'英国','GB'),(null,'法国','FR');
第四步:开始准备mybatis的配置工作,这里使用最常用的xml方式配置。
核心配置文件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>
<!--引入数据库连接池的必须参数-->
<properties resource="jdbc.properties"/>
<settings>
<!--设置mybatis打印log的参数-->
<setting name="logImpl" value="LOG4J"/>
<!--设置开始下划线转驼峰的自动映射-->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!--设置懒加载-->
<!--<setting name="aggressiveLazyLoading" value="false"/>-->
</settings>
<typeAliases>
<!--批量定义包中的类的别名,在后面使用的时候更方便了。别名是类名(首字母大小写都可以)-->
<package name="com.zale.mybatis.domain"/>
</typeAliases>
<environments default="development">
<!--运行环境配置-->
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="UNPOOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--映射文件Mapper的位置-->
<mapper resource="com/zale/mybatis/mapper/CountryMapper.xml"/>
</mappers>
</configuration>
第五步:创建数据库中对应的表的JavaBean
package com.zale.mybatis.domain;
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;
}
}
第六步:创建对应这个表的操作映射文件CountryMapper.xml。建议在resources目录下创建对应包结构的目录结构,然后再在对应目录结构下创建mapper文件。
(目录结构一定要对应mybatis-config.xml中的配置路径<mapper resource="com/zale/mybatis/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="com.zale.mybatis.mapper.CountryMapper">
<select id="selectAll" resultType="Country">
select * from country
</select>
</mapper>
第七步:配置Log4j的输出配置
#全局配置
log4j.rootLogger = ERROR, stdout
#mybatis 配置
log4j.logger.com.zale.mybatis.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
第八步:所有的配置终于都完成了。我们可以开始写测试代码,让我们的mybatis跑起来了。
package com.zale.mybatis.service;
import com.zale.mybatis.domain.Country;
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.Reader;
import java.util.List;
public class CountryMapperTest extends BaseMapperTest{
private static SqlSessionFactory sqlSessionFactory;
@Test
public void testSelectAll() throws Exception {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
reader.close();
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
List<Country> selectAll = sqlSession.selectList("selectAll");
printList(selectAll);
} finally {
sqlSession.close();
}
}
private void printList(List<Country> selectAll) {
for (Country c :
selectAll) {
System.out.printf("%-4d%4s%4s\n",c.getId(),c.getCountryname(),c.getCountrycode());
}
}
}
最终程序打印查询出来的结果,mybatis的helloworld就完成了。