MyBatis源码解读 | 使用MyBatis操作数据库

本篇文章主要介绍了使用MyBatis框架完成数据库的增、删、改、查操作 。
准备工作
运行schema.sql和data.sql脚本文件中的 SQL 语句创建t_user表并添加部分测试数据 。
schema.sql:
DROP TABLE IF EXISTS `t_user`;create table t_user(idint auto_increment primary key COMMENT '主键',usernamevarchar(64) null COMMENT '用户名',nick_namevarchar(64) null COMMENT '昵称',passwordvarchar(64) null COMMENT '密码',phonevarchar(32) null COMMENT '手机号',create_time varchar(64) null COMMENT '创建时间') ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='用户表';data.sql:
insert into t_user(`username`, `nick_name`, `password`, `phone`, `create_time`)values ('user01', 'user01', '123456', '15900001111', '2022-07-14 16:00:00');insert into t_user(`username`, `nick_name`, `password`, `phone`, `create_time`)values ('user02', 'user02', '123456', '15900001111', '2022-07-14 16:00:00');insert into t_user(`username`, `nick_name`, `password`, `phone`, `create_time`)values ('user03', 'user03', '123456', '15900001111', '2022-07-14 16:00:00');insert into t_user(`username`, `nick_name`, `password`, `phone`, `create_time`)values ('user04', 'user04', '123456', '15900001111', '2022-07-14 16:00:00');使用MyBatis框架操作数据库步骤:
(1)定义JAVA实体
User.java
@Datapublic class User {private Integer id;private String username;private String nickName;private String password;private String phone;private String createTime;}(2)定义MApper接口
UserDao.java
public interface UserDao {void insert(User user);void update(User user);User findByUsername(String username);void deleteById(Integer id);}(3)编写XML映射文件
UserDao.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.jasmine.mybatis.demo.dao.UserDao"><insert id="insert" parameterType="User">insert into t_user(`username`, `nick_name`, `password`, `phone`, `create_time`)values(#{username}, #{nickName}, #{password}, #{phone}, #{createTime})</insert><update id="update" parameterType="User">update t_userset username = #{username}, nick_name = #{nickName}, password = #{password}, phone = #{phone}, create_time = #{createTime}where id = #{id}</update><select id="findByUsername" parameterType="String" resultType="User">select id, username, nick_name as nickName, password, phone, create_time as createTimefrom t_user where username = #{username}</select><delete id="deleteById" parameterType="Integer">delete from t_user where id = #{id}</delete></mapper>(4)编写MyBatis主配置文件
MyBatis使用 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><typeAliases><typeAlias alias="User" type="com.jasmine.mybatis.demo.entity.User" /></typeAliases><environments default="development"><environment id="development"><transactionManager type="JDBC" /><dataSource type="POOLED"><property name="driver" value=https://www.isolves.com/it/cxkf/kj/2022-07-15/"com.MySQL.cj.jdbc.Driver" />(5)编写测试类
【MyBatis源码解读 | 使用MyBatis操作数据库】Demo.java
public class Demo {public static void main(String[] args) throws IOException {// 获取配置文件输入流InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");// 创建 SqlSessionFactorySqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);// 获取 SqlSessionSqlSession sqlSession = sqlSessionFactory.openSession();// 获取 Mapper 接口UserDao userDao = sqlSession.getMapper(UserDao.class);// 新增一个用户User newUser = new User();newUser.setUsername("new-user");newUser.setNickName("新建的用户(修改前)");newUser.setPassword("123123");newUser.setPhone("13900001111");newUser.setCreateTime("2022-07-14 16:00:00");userDao.insert(newUser);// 根据用户名获取用户信息User user = userDao.findByUsername("new-user");System.out.println("########## 修改前用户信息 ##########");System.out.println(new Gson().toJson(user));// 修改用户信息user.setUsername("update-user");user.setNickName("新建的用户(修改后)");userDao.update(user);user = userDao.findByUsername("update-user");System.out.println("########## 修改后用户信息 ##########");System.out.println(new Gson().toJson(user));// 删除用户userDao.deleteById(user.getId());}}


推荐阅读