文章目录
前沿
我们使用IDEA来搭建环境、运行程序,环境的配置不在此篇文章范围内
1.为什么使用 MyBatis
在我们传统的 JDBC 中,我们除了需要自己提供 SQL 外,还必须操作 Connection、Statment、ResultSet,不仅如此,为了访问不同的表,不同字段的数据,我们需要些很多雷同模板化的代码,闲的繁琐又枯燥。
而我们在使用了 MyBatis 之后,只需要提供 SQL 语句就好了,其余的诸如:建立连接、操作 Statment、ResultSet,处理 JDBC 相关异常等等都可以交给 MyBatis 去处理,我们的关注点于是可以就此集中在 SQL 语句上,关注在增删改查这些操作层面上。
并且 MyBatis 支持使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
2.第一个 MyBatis 程序
第一步:准备数据库
首先我们创建一个数据库【mybatis】,编码方式设置为 UTF-8,然后再创建一个名为【student】的表,插入几行数据:
DROP DATABASE IF EXISTS mybatis;
CREATE DATABASE mybatis DEFAULT CHARACTER SET utf8;
use mybatis;
CREATE TABLE student(
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(255) NOT NULL,
age int(11) NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO student VALUES(1,'路飞',18);
INSERT INTO student VALUES(2,'索隆',19);
INSERT INTO student VALUES(3,'路飞',20);
第二步:创建工程
在 IDEA 中新建一个Maven工程,并命名为【HelloMybatis】
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>qxt</groupId>
<artifactId>HelloMybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<name>HelloMybatis</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!--有时候版本不对会出问题-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<!-- ********************** Mybatis依赖 ********************** -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.4</version>
</dependency>
</dependencies>
<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
<!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
<!--解决找不到配置文件的方法-->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resource</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
</project>
- 注意注释:<!–解决找不到配置文件的方法–>
- 解析:
mybatis默认找的映射文件路径是src/main/resources,如果放在src/main/java下的一个包中,则需要在该项目的pom.xml文件中加入:
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
此时找的就是src/main/java下的mapper所在的包中,要是还想继续能找到
src/main/resource下的映射文件,加个resource属性:
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resource</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
第三步:创建实体类
在源文件夹java下创建Package【pojo】,pojo下新建实体类【Student】,用于映射表 student:
package pojo;
public class Student
{
private int id;
private String name;
private int age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
第四步:配置文件 mybatis-config.xml
在main文件夹下新建resource目录resource,在resource中新建 MyBaits 的主配置文件 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>
<!-- 别名 -->
<!--使得在后续配置文件StudentMapper.xml中使用resultType的时候,可以直接使用Student,而不必写全pojo.Category-->
<typeAliases>
<package name="pojo"/>
</typeAliases>
<!-- 数据库环境 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="qxt2000928"/>
</dataSource>
</environment>
</environments>
<!-- 映射文件 -->
<mappers>
<mapper resource="pojo/StudentMapper.xml"/>
</mappers>
</configuration>
第五步:配置文件 StudentMapper.xml
在 文件夹【pojo】下新建一个【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">
<!--数据库映射文件-->
<!--表示命名空间是pojo,在后续调用sql语句的时候,会用到它-->
<mapper namespace="pojo">
<!--这条sql语句用id: listStudent 进行标示以供后续代码调用。resultType="Student" 表示返回的数据和Student类关联起来,
这里本应该使用的是 pojo.Student, 但是因为上一步配置了别名,所以直接使用Student就行了-->
<select id="listStudent" resultType="Student">
select * from student
</select>
<select id="aStudent" resultType="student">
select * from student where id = 1
</select>
</mapper>
- 由于上面mybatis-config.xml配置了<typeAliases> 别名,所以在这里的 resultType 可以直接写 Student,而不用写类的全限定名 pojo.Student
- namespace 属性其实就是对 SQL 进行分类管理,实现不同业务的 SQL 隔离
- resultType后跟输出的类型
第六步:编写测试类
在 Package【test】中创建测试类【TestMyBatis】:
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 pojo.Student;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* 测试类
*/
public class TestMyBatis
{
public static void main(String[] args) throws IOException
{
// 根据 mybatis-config.xml 配置的信息得到 sqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 然后根据 sqlSessionFactory 得到 session
SqlSession session = sqlSessionFactory.openSession();
// 最后通过 session 的 selectList() 方法调用 sql 语句 listStudent。listStudent这个就是在配置文件StudentMapper.xml中那条sql语句设置的id。
List<Student> listStudent = session.selectList("listStudent");
for (Student student : listStudent) {
System.out.println("ID:" + student.getId() + ",NAME:" + student.getName() + ",AGE:" + student.getAge());
}
List<Student> listStudent2 = session.selectList("aStudent");
for (Student student : listStudent2) {
System.out.println("ID:" + student.getId() + ",NAME:" + student.getName() + ",AGE:" + student.getAge());
}
}
}
第七步:运行
输出:
ID:1,NAME:路飞,AGE:18
ID:2,NAME:索隆,AGE:19
ID:3,NAME:山治,AGE:20
ID:1,NAME:路飞,AGE:18
2.基本原理
- 应用程序找 MyBatis 要数据
- MyBatis 从数据库中找来数据
1.通过 mybatis-config.xml 定位哪个数据库
2.通过 StudentMapper.xml 执行对应的 sql 语句
3.基于 StudentMapper.xml 把返回的数据库封装在 Student 对象中
4.把多个 Student 对象装载一个 Student 集合中 - 返回一个 Student 集合