最近在读刘增辉老师所著的《MyBatis从入门到精通》一书,颇有收获,因而将本身学习的过程以博客形式输出,若有错误,欢迎指正,如帮助到你,不胜荣幸!html
2001年,Clinton Begin发起了一个名为iBATIS的开源项目,最初侧重于密码软件的研发,后来发展成为一款基于Java的持久层框架。java
2004年,Clinton将iBATIS的名字和源码捐赠给了Apache软件基金会。mysql
2010年,核心开发团队决定离开Apache软件基金会,而且将iBATIS更名为MyBatis。git
MyBatis是一款优秀的支持自定义SQL查询、存储过程和高级映射的持久层框架,消除了几乎全部的JDBC代码和参数的手动设置以及结果集的检索。MyBatis可使用XML或注解进行配置和映射,MyBatis经过将参数映射到配置的SQL造成最终执行的SQL语句,最后将执行SQL的结果映射成Java对象返回。github
与其余的ORM(对象关系映射)框架不一样,MyBatis并无将Java对象与数据库表关联起来,而是将Java方法与SQL语句关联。sql
说明:以上内容了解下便可,由于按个人风格,特别不喜欢纯理论纯文字的东西,看过我以往博客的读者可能有这个意识,我更喜欢具体代码实战,好比如何使用一个新技术,某一段代码是为了解决什么问题……数据库
关于Maven的相关内容,你们能够参考我以前的博客Spring入门(四):使用Maven管理Spring项目。apache
我一直认为,理解一门技术最好的方式,是经过一个具体的例子,好比Hello World,哈哈。api
因此,首先咱们要新建个Maven项目,使用IDEA新建Maven项目的方法以下所示:微信
刚新建完的Maven项目结构以下所示:
默认生成的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>com.zwwhnly</groupId> <artifactId>mybatis-action</artifactId> <version>1.0-SNAPSHOT</version> </project>
首先,咱们设置源代码的编码方式为UTF-8:
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties>
接着,设置编译源代码的JDK版本,这里暂时用1.6,可根据本身的实际须要修改,好比修改为1.8:
<build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </build>
而后,添加剧要的MyBatis的依赖坐标和mysql驱动的依赖坐标:
<dependencies> <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> </dependencies>
最后,添加下用到的Log4j、JUnit的依赖坐标,最终的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>com.zwwhnly</groupId> <artifactId>mybatis-action</artifactId> <version>1.0-SNAPSHOT</version> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <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>junit</groupId> <artifactId>junit</artifactId> <version>4.12</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.6</source> <target>1.6</target> </configuration> </plugin> </plugins> </build> </project>
在IDEA中,若是没有特殊配置过,修改完pom文件,须要手动导入下,不然是下图这样的状况:
怎么手动导入呢?点击下IDEA右下角提示的Import Changes便可。
至此,Maven项目建立完毕。
首先执行以下语句建立数据库mybatis_action_db:
CREATE DATABASE mybatis_action_db DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
而后执行以下语句建立表country,并添加一些数据:
use mybatis_action_db; CREATE TABLE country ( id INT NOT NULL AUTO_INCREMENT, countryname VARCHAR(255) NULL, countrycode VARCHAR(255) NULL, PRIMARY KEY (id) ); INSERT country(countryname, countrycode) VALUES ('中国', 'CN'), ('美国', 'US'), ('俄罗斯', 'RU'), ('英国', 'GB'), ('法国', 'FR');
首先在src/main/resources目录下建立mybatis-config.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> <settings> <setting name="logImpl" value="LOG4J"/> </settings> <typeAliases> <package name="com.zwwhnly.mybatisaction.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_action_db"/> <property name="username" value="root"/> <property name="password" value=""/> </dataSource> </environment> </environments> <mappers> <mapper resource="com/zwwhnly/mybatisaction/mapper/CountryMapper.xml"/> </mappers> </configuration>
配置简单讲解:
在src/main/java下新建包:com.zwwhnly.mybatisaction,而后在这个包下再建立包:model。
在model包下建立数据库表country表对应的实体类Country:
package com.zwwhnly.mybatisaction.model; public class Country { private Integer id; private String countryname; private String countrycode; // 按Alt+Insert快捷键生成get和set方法 }
在src/main/resources下建立目录com/zwwhnly/simple/mapper目录,而后在该目录下建立CountryMapper.xml文件,为了后续更快速的建立Mapper.xml文件,咱们能够参考上面的添加mybatis-config.xml模版的方法,这里再也不赘述。
最终的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.zwwhnly.mybatisaction.mapper.CountryMapper"> <select id="selectAll" resultType="Country"> SELECT id,countryname,countrycode from country </select> </mapper>
配置简单讲解:
在src/main/resources下新建log4j.properties配置文件,输入以下内容:
log4j.rootLogger=ERROR, stdout log4j.logger.com.zwwhnly.mybatisaction.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
在src/test/java下建立包:com.zwwhnly.mybatisaction.mapper,而后建立测试类CountryMapperTest类,代码以下:
package com.zwwhnly.mybatisaction.mapper; import com.zwwhnly.mybatisaction.mapper.model.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.junit.BeforeClass; import org.junit.Test; import java.io.IOException; import java.io.Reader; import java.util.List; public class CountryMapperTest extends BaseMapperTest { 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 e) { e.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()); } } }
运行测试代码,输出日志以下:
DEBUG [main] - ==> Preparing: SELECT id,countryname,countrycode from country
DEBUG [main] - ==> Parameters:
TRACE [main] - <== Columns: id, countryname, countrycode
TRACE [main] - <== Row: 1, 中国, CN
TRACE [main] - <== Row: 2, 美国, US
TRACE [main] - <== Row: 3, 俄罗斯, RU
TRACE [main] - <== Row: 4, 英国, GB
TRACE [main] - <== Row: 5, 法国, FR
DEBUG [main] - <== Total: 5
1 中国 CN
2 美国 US
3 俄罗斯 RU
4 英国 GB
5 法国 FR
源码地址:https://github.com/zwwhnly/mybatis-action.git,欢迎下载。
刘增辉《MyBatis从入门到精通》
欢迎扫描下方二维码关注微信公众号:「申城异乡人」,博客内容会同步更新。