目录
前言
好记性不如烂笔头
项目目录
一、创建 Maven 项目
1. 菜单上选择 File-> New->Project
2.选择Maven,然后点击Next
3.输入GroupId和ArtifactId,点击Next
GroupId 填 com.fang.mybatis,ArtifactId 填 helloMybatis
4.点击Finish
二、POM配置
1.配置 JDK 版本和编码方式
pom.xml 配置如下
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
设置后, 编码方式为 UTF-8, JDK 版本为 1.8
2.设置资源文件路径
Maven 中默认是只会打包 resource下的资源文件。如果我们的文件不放在resource, 则需要通过配置告知Maven。
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
3.添加依赖
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!--数据库 mysql 驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
<!-- 实现slf4j接口并整合 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.10.0</version>
</dependency>
<!--junit 测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
添加日志是为了在测试时可以输出sql语句。
4.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.fang.mybatis</groupId>
<artifactId>helloMybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
<dependencies>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!--数据库 mysql 驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
<!-- 实现slf4j接口并整合 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.10.0</version>
</dependency>
<!--junit 测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
三、初始化数据
1.建库脚本
CREATE DATABASE IF NOT EXISTS `mybatis` DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
2.创建student表
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`student_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '编号',
`name` VARCHAR(20) DEFAULT NULL COMMENT '姓名',
`phone` VARCHAR(20) DEFAULT NULL COMMENT '电话',
`email` VARCHAR(50) DEFAULT NULL COMMENT '邮箱',
`sex` TINYINT(4) DEFAULT NULL COMMENT '性别',
`locked` TINYINT(4) DEFAULT NULL COMMENT '状态(0:正常,1:锁定)',
`gmt_created` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '存入数据库的时间',
`gmt_modified` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改的时间',
PRIMARY KEY (`student_id`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='学生表';
3.插入测试数据
INSERT INTO `student`(`name`, phone, email, sex, locked)
VALUES
('小明', 13821378270, 'xiaoming@mybatis.cn', 1, 0),
('小丽', 13821378271, 'xiaoli@mybatis.cn', 0, 0),
('小刚', 13821378272, 'xiaogang@mybatis.cn', 1, 0),
('小花', 13821378273, 'xiaohua@mybatis.cn', 0, 0),
('小强', 13821378274, 'xiaoqiang@mybatis.cn', 1, 0),
('小红', 13821378275, 'xiaohong@mybatis.cn', 0, 0);
四、配置 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="config.properties"/>
<settings>
<setting name="logImpl" value="LOG4J" />
</settings>
<typeAliases>
<package name="com.fang.mybatis.entity"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">
<property name="" value=""/>
</transactionManager>
<dataSource type="POOLED">
<!-- <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"/>-->
<property name="driver" value="${database.driver}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.fang.mybatis.mapper"/>
</mappers>
</configuration>
1.配置properties,指向配置文件,配置文件中包含数据源信息
2.配置settings,在本项目中, 主要是为了配置日志输出。 pom.xml中配置的是 log4j, 因此此处的日志实现值是 LOG4J。
3.配置 typeAliases,类型别名是为 Java 类型设置一个短的名字。它只和 XML 配置有关,存在的意义仅在于用来减少类完全限定名的冗余。
那么在mybatis中, Student可以用在任何使用com.fang.mybatis.entity.Student的地方。但一般来说entity都会有很多, 因此这样配置太繁琐了, mybatis支持指定包名, 会使用类的首字母小写的类限定名作为别名。
4.配置environments,对应的是数据库相关的属性。我们可以配置多个环境,但每个 SqlSessionFactory 实例只能选择其一。在本项目中, 我们只配置一个即可。数据库时刚刚我们创建的mybatis。
5.配置 mappers,同理,可以单个配置,也可以通过扫描包来识别。该配置会扫描指定包中的所有 .xml 文件,这些文件包含着mybatis的 SQL 语句和映射配置文件。后续会创建。
五、配置config.properties
database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/mybatis
database.username=root
database.password=123456
六、配置log4j.properties
log4j.rootLogger=INFO,Console
log4j.additivity.org.apache=true
log4j.logger.com.fang.mybatis.mapper=TRACE
#Console
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.org.apache=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
七、创建实体类和对应的Mapper.xml
1.创建实体类
实体类,属性需要与数据库表中的字段一一对应,并有对应的getter和setter、toString方法
package com.fang.mybatis.entity;
import java.util.Date;
public class Student {
private Integer studentId;
private String name;
private String phone;
private String email;
private Byte sex;
private Byte locked;
private Date gmtCreated;
private Date gmtModified;
/**
* 以下部分为setter和getter, 省略
*/
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Byte getSex() {
return sex;
}
public void setSex(Byte sex) {
this.sex = sex;
}
public Byte getLocked() {
return locked;
}
public void setLocked(Byte locked) {
this.locked = locked;
}
public Date getGmtCreated() {
return gmtCreated;
}
public void setGmtCreated(Date gmtCreated) {
this.gmtCreated = gmtCreated;
}
public Date getGmtModified() {
return gmtModified;
}
public void setGmtModified(Date gmtModified) {
this.gmtModified = gmtModified;
}
@Override
public String toString() {
return "Student{" +
"studentId=" + studentId +
", name='" + name + '\'' +
", phone='" + phone + '\'' +
", email='" + email + '\'' +
", sex=" + sex +
", locked=" + locked +
", gmtCreated=" + gmtCreated +
", gmtModified=" + gmtModified +
'}';
}
}
2.创建 Mapper 接口和 Mapper.xml
StudentMapper.java
package com.fang.mybatis.mapper;
import com.fang.mybatis.entity.Student;
import java.util.List;
public interface StudentMapper {
/**
*
* @return
*/
List<Student> selectAll();
}
StudentMapper.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.fang.mybatis.mapper.StudentMapper">
<resultMap id="BaseResultMap" type="com.fang.mybatis.entity.Student">
<id column="student_id" jdbcType="INTEGER" property="studentId" />
<result column="name" jdbcType="VARCHAR" property="name" />
<result column="phone" jdbcType="VARCHAR" property="phone" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="sex" jdbcType="TINYINT" property="sex" />
<result column="locked" jdbcType="TINYINT" property="locked" />
<result column="gmt_created" jdbcType="TIMESTAMP" property="gmtCreated" />
<result column="gmt_modified" jdbcType="TIMESTAMP" property="gmtModified" />
</resultMap>
<sql id="Base_Column_List">
student_id, name, phone, email, sex, locked, gmt_created, gmt_modified
</sql>
<select id="selectAll" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from student
</select>
</mapper>
配置了结果映射和 sql 语句, 其中 sql 中的 id(selectAll) 与Mapper中的方法名一致。
六.测试
package com.fang.mybatis;
import com.fang.mybatis.entity.Student;
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.Reader;
import java.util.List;
public class StudentMapperTest {
private static SqlSessionFactory sqlSessionFactory;
@BeforeClass
public static void init() throws Exception{
try {
Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testSelectList() {
SqlSession sqlSession = null;
try {
sqlSession = sqlSessionFactory.openSession();
List<Student> students = sqlSession.selectList("selectAll");
for (int i = 0; i < students.size(); i++) {
System.out.println(students.get(i));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (sqlSession != null) {
sqlSession.close();
}
}
}
}
执行结果:
总结
1.通过 Resources 工具类读取 mybatis-config.xml, 存入 Reader;
2.SqlSessionFactoryBuilder使用上一步获得的reader创建SqlSessionFactory对象;
3.通过 sqlSessionFactory 对象获得SqlSession;
4.SqlSession对象通过selectList方法找到对应的“selectAll”语句, 执行SQL查询。
5.底层通过 JDBC 查询后获得ResultSet, 对每一条记录, 根据resultMap的映射结果映射到Student中, 返回List。
6.最后记得关闭 SqlSession。