什么是Mybatis
MyBatis 是一款优秀的
持久层框架
,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
持久化
- 因为内存有断电即失的特性,所以需要进行数据持久化
- 持久化就是将程序的数据在持久状态和瞬时状态转化的过程
持久层
持久层,可以理解成数据保存在数据库或者硬盘一类可以保存很长时间的设备里面,不像放在内存中那样断电就消失了,也就是把数据存在持久化设备上
Mybatis的简单使用(Maven项目)
pom文件引入jar包
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
创建工具类
package cn.com.scitc.mybatis.utils;
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 java.io.IOException;
import java.io.InputStream;
public class MybatisUtil {
private static SqlSessionFactory sqlSessionFactory;
static {
InputStream inputStream = null;
try {
//用输入流来读取xml文件
inputStream = Resources.getResourceAsStream("mybatis-config.xml");
} catch (IOException e) {
e.printStackTrace();
}
//创建SqlSession工厂
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
public static SqlSession getSqlSession(){
//创建并返回SqlSession
return sqlSessionFactory.openSession();
}
}
创建实体类
package cn.com.scitc.model;
public class User {
private Integer id;
private String name;
private String mobile;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
}
创建mybatis配置文件
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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!-- JDBC配置 -->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/webapp1901"/>
<property name="username" value="root"/>
<property name="password" value="lishuang001219"/>
</dataSource>
</environment>
</environments>
<mappers>
<!-- 绑定Mapper配置文件 -->
<mapper resource="UserMapper.xml"/>
<!-- resource下的Mapper资源存在多层目录结构时的写法 -->
<mapper resource="cn/com/scitc/webapp1901/mapper/UserMapper.xml"/>
</mappers>
</configuration>
创建Mapper接口文件
package cn.com.scitc.test.mapper;
import cn.com.scitc.test.pojo.User;
public interface UserMapper {
public User findById(Integer id);
}
创建Mapper配置文件
UserMapper.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">
<!-- namespace命名空间:对应一个Mapper接口 -->
<mapper namespace="cn.com.scitc.mapper.UserMapper">
<!-- sql语句 -->
<!-- id对应接口中定义的方法 resultType表示结果集类型 -->
<select id="selectUser" resultType="cn.com.scitc.model.User">
select * from user where id = #{id}
</select>
</mapper>
创建Dao文件
package cn.com.scitc.test.dao;
import cn.com.scitc.test.mapper.UserMapper;
import cn.com.scitc.test.pojo.User;
import cn.com.scitc.test.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
public class UserDao implements UserMapper{
public User findById(Integer id) {
//获取SqlSession
try(SqlSession session = MybatisUtils.getSqlSession()){
//获取Mapper,执行其中方法
UserMapper mapper = session.getMapper(UserMapper.class);
return mapper.findById(id);
}
}
}
编写测试类
package cn.com.scitc.test;
import cn.com.scitc.test.dao.UserDao;
import cn.com.scitc.test.pojo.User;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class UserDaoTest {
@Test
void findById() {
UserDao userDao = new UserDao();
User user = userDao.findById(1);
System.out.println(user.getName());
Assertions.assertEquals("张三",user.getName());
}
}
项目基本结构
![](https://img.jcxiaozhan.top/Mybatis%E5%85%A5%E9%97%A8%E4%B8%80.jpg#pic_center)
mybatis-generator的简单使用
{% note warning flat %}
注:此插件主要用于自动生成实体类、Mapper接口和Mapper配置文件。mybatis配置文件和Dao层文件需要根据实际应用场景对照生成的文件自行编写
{% endnote %}
编写pom文件
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!-- 添加插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.0</version>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
</dependencies>
<configuration>
<!-- 设置生成的文件覆盖源文件 -->
<overwrite>true</overwrite>
</configuration>
</plugin>
编写mybatis-generator配置文件
generatorConfig.xml
<!DOCTYPE generatorConfiguration PUBLIC
"-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="simple" targetRuntime="MyBatis3Simple">
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/webapp1901" userId="root" password="lishuang001219"/>
<!--实体存放位置-->
<javaModelGenerator targetPackage="cn.com.scitc.webapp1901.pojo" targetProject="src/main/java"/>
<!--Mapper.xml存放位置-->
<sqlMapGenerator targetPackage="cn.com.scitc.webapp1901.mapper" targetProject="src/main/resources"/>
<!--Mapper接口存放位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="cn.com.scitc.webapp1901.mapper" targetProject="src/main/java"/>
<!--需要生成的表-->
<table tableName="student" />
</context>
</generatorConfiguration>
双击一键生成代码
![](https://img.jcxiaozhan.top/Mybatis%E5%85%A5%E9%97%A8%E4%BA%8C.jpg#pic_center)