目录
什么是 MyBatis
MyBatis 是⼀款优秀的持久层框架,它⽀持⾃定义 SQL、存储过程以及⾼级映射. MyBatis 去除了⼏乎所有的 JDBC 代码以及设置参数和获取结果集的⼯作.
简单来说 MyBatis 是更简单完成程序和数据库交互的⼯具,也就是更简单的操作和读取数据库⼯具.
(它的底层是基于 JDBC 的,就像 Spring 底层是基于 Servlet 一样,都是为了让操作更简便)
MyBatis 环境的搭建
分两步 :
- 添加 MyBatis 依赖
- 设置 MyBatis 配置
添加 MyBatis 依赖
注意 : 这个时候项目是运行不起来的, 因为我们添加了 MyBatis 依赖, 服务器就需要知道它具体要连接哪台数据库, 以及账户密码等, 这就需要设置配置了.
设置 MyBatis 配置
# 数据库连接配置(mycnblog 对应你要操作的数据库名)
spring.datasource.url=jdbc:mysql://localhost:3306/mycnblog?characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# 配置 mybatis xml 的⽂件路径
# 在 resources/mybatis 创建所有表的 xml ⽂件
mybatis.mapper-locations=classpath:mybatis/**Mapper.xml
# 配置 MyBatis 执行时打印 SQL(可选配置)
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
logging.level.com.example.demo=debug
根据 MyBatis 写法完成数据库操作
查询操作(无参)
先来看看数据库里有啥 :
我们就对 userinfo 进行操作 :
定义接口
首先得定义 model 层的 Userinfo 类 :
@Data
public class Userinfo {
private int id;
private String username;
private String password;
private String photo;
private LocalDateTime createtime;
private LocalDateTime updatetime;
private int state;
}
再在 dao 层定义接口 :
@Mapper //数据持久层标志
public interface UserMapper {
//查询声明
//getAll 是操作数据库的方法名
List<Userinfo> getAll();
}
使用 XML 实现接口
在 resources 下 创建 mybatis 目录(配置中定义的), 然后在该目录下定义一个 UserMapper.xml (Mapper 必须有, 配置中规定的).
查询操作 :
<?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.example.demo.dao.UserMapper">
<select id="getAll" resultType="com.example.demo.model.Userinfo">
select * from userinfo
</select>
</mapper>
select 查询操作
id=“getAll” 实现接口中的方法
resultType=“com.example.demo.model.Userinfo” 返回的数据类型
select * from userinfo 具体的 sql 语句(注意不要加分号)
在测试类中进行测试 :
@SpringBootTest //项目运行在 spring 容器中
class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
void getAll() {
List<Userinfo> list = userMapper.getAll();
System.out.println(list);
}
}