简介
MyBatis是一个Java持久层框架,它通过XML描述符或注解把对象与存储过程或SQL语句关联起来。mybatis 可以将 preparedStatement 中的输入参数自动进行映射,将查询结果集灵活映射成 java 对象。所以使用 mybatis 我们就可以不用写原生 jdbc 程序,并且能很好的避免 原生 jdbc 中 SQL 注入的问题。
一个完整 mybatis 程序的操作过程
1 配置 mybatis 的全局配置文件 SqlMapConfig.xml(名称不固定),该文件配置了数据源。事务等 mybatis 运行环境。
2 创建 java 文件,封装数据库对象。
3 配置映射文件 mapper.xml(名称不固定), 在该文件中,我们将对数据库封装的对象进行 SQL 语句操作。并在全局配置文件中通过mapper
加载该映射文件。
4 另外创建java 文件,通过配置文件,加载 mybatis 运行环境,创建 SqlSessionFactory
会话工厂(SqlSessionFactory
在实际使用时按单例方式)。
5 通过 SqlSessionFactory
创建 SqlSession
。SqlSession
是一个面向用户接口(提供操作数据库方法),实现对象是线程不安全的,建议sqlSession
应用场合在方法体内。
6 调用sqlSession
的方法去操作数据。如果需要提交事务,需要执行SqlSession
的commit()
方法。
7 释放资源,关闭SqlSession
。
mybatis 实例
下面我们通过一个具体的例子来实现 mybatis 的查询功能。
前提条件
首先是运行 mybatis 需要的前提条件,在这里我们需要连接数据库,所以需要 java 连接 MySQL 数据库的 jar 包,其次还需要 mybatis 的核心包,如果还需要用到日志功能的话还需要 log4j.jar
等,mybatis 的相关依赖可以在 GitHub 上找到:mybatis 地址
我们通过 maven 来导入具体需要的 jar 包,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>cn.itcast</groupId>
<artifactId>mybatis</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<!-- mysql 驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency>
<!-- test 测试文件 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- mybatis 核心jar包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!-- mybatis 附加功能包,如日志功能等 -->
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant-launcher</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>org.ow2.asm</groupId>
<artifactId>asm</artifactId>
<version>5.2</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.5</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.22.0-GA</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.3</version>
</dependency>
<dependency>
<groupId>ognl</groupId>
<artifactId>ognl</artifactId>
<version>3.1.16</version>
</dependency>
<dependency>
<