MyBatis 基本操作

MyBatis 是一个优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。以下是 MyBatis 的基本操作步骤,包括配置文件的创建、映射文件的编写、Mapper 接口的定义以及如何在应用程序中使用 MyBatis 进行 CRUD 操作。

1. 添加 MyBatis 依赖

首先,在 pom.xml 文件中添加 MyBatis 的依赖:

XML 复制代码
<dependencies>
    <!-- MyBatis 依赖 -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.7</version>
    </dependency>
    <!-- MySQL 驱动依赖 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.23</version>
    </dependency>
    <!-- JUnit 测试依赖 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.2</version>
        <scope>test</scope>
    </dependency>
</dependencies>

2. 创建 MyBatis 主配置文件

src/main/resources 目录下创建 mybatis-config.xml 文件,配置数据库连接和其他 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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mydb?useSSL=false&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="password"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="org/example/mapper/EmpMapper.xml"/>
    </mappers>
</configuration>

3. 创建实体类

src/main/java/org/example/model 目录下创建 Emp 实体类:

java 复制代码
package org.example.model;

public class Emp {
    private int id;
    private String name;
    private String position;
    private double salary;

    // Getters and Setters
    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 String getPosition() {
        return position;
    }

    public void setPosition(String position) {
        this.position = position;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", position='" + position + '\'' +
                ", salary=" + salary +
                '}';
    }
}

4. 创建 Mapper 接口

src/main/java/org/example/mapper 目录下创建 EmpMapper 接口:

java 复制代码
package org.example.mapper;

import org.example.model.Emp;

public interface EmpMapper {
    Emp selectById(int id);
    void insert(Emp emp);
    void update(Emp emp);
    void delete(int id);
}

5. 创建 Mapper XML 文件

src/main/resources/org/example/mapper 目录下创建 EmpMapper.xml 文件,定义 SQL 语句:

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="org.example.mapper.EmpMapper">
    <select id="selectById" resultType="org.example.model.Emp">
        SELECT * FROM emp WHERE id = #{id}
    </select>

    <insert id="insert" parameterType="org.example.model.Emp">
        INSERT INTO emp (name, position, salary) VALUES (#{name}, #{position}, #{salary})
    </insert>

    <update id="update" parameterType="org.example.model.Emp">
        UPDATE emp SET name = #{name}, position = #{position}, salary = #{salary} WHERE id = #{id}
    </update>

    <delete id="delete" parameterType="int">
        DELETE FROM emp WHERE id = #{id}
    </delete>
</mapper>

6. 编写测试类

src/test/java/org/example 目录下创建 MybatisTest 类,编写测试方法:

java 复制代码
package org.example;

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 org.example.mapper.EmpMapper;
import org.example.model.Emp;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.Reader;

public class MybatisTest {
    private SqlSessionFactory sqlSessionFactory;

    @Before
    public void setUp() throws IOException {
        String resource = "org/example/mybatis-config.xml";
        Reader reader = Resources.getResourceAsReader(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
    }

    @After
    public void tearDown() {
        // 关闭资源
    }

    @Test
    public void testSelectById() {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            EmpMapper mapper = session.getMapper(EmpMapper.class);
            Emp emp = mapper.selectById(1);
            System.out.println(emp);
        }
    }

    @Test
    public void testInsert() {
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            EmpMapper mapper = session.getMapper(EmpMapper.class);
            Emp emp = new Emp();
            emp.setName("John Doe");
            emp.setPosition("Developer");
            emp.setSalary(75000.0);
            mapper.insert(emp);
        }
    }

    @Test
    public void testUpdate() {
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            EmpMapper mapper = session.getMapper(EmpMapper.class);
            Emp emp = new Emp();
            emp.setId(1);
            emp.setName("Jane Doe");
            emp.setPosition("Senior Developer");
            emp.setSalary(85000.0);
            mapper.update(emp);
        }
    }

    @Test
    public void testDelete() {
        try (SqlSession session = sqlSessionFactory.openSession(true)) {
            EmpMapper mapper = session.getMapper(EmpMapper.class);
            mapper.delete(1);
        }
    }
}

7. 运行测试

在 IntelliJ IDEA 中,右键点击 MybatisTest 类,选择 Run 'MybatisTest' 来运行测试方法。确保数据库中有相应的表和数据。

相关推荐
ᝰꫝꪉꪯꫀ36110 小时前
JavaWeb——Mybatis
java·开发语言·后端·mybatis
A_Tai233333314 小时前
MyBatis高级扩展
java·开发语言·mybatis
岁岁岁平安15 小时前
springboot实战(19)(条件分页查询、PageHelper、MYBATIS动态SQL、mapper映射配置文件、自定义类封装分页查询数据集)
java·spring boot·后端·mybatis·动态sql·pagehelper·条件分页查询
计算机学姐15 小时前
基于SSM的宠物领养平台
java·vue.js·spring·maven·intellij-idea·mybatis·宠物
真上帝的左手15 小时前
数据库-MySQL-MybatisPlus整合多数据源
数据库·mysql·mybatis
真上帝的左手15 小时前
数据库-MySQL-Mybatis源码解析-设计模式角度
数据库·mysql·mybatis
对酒当歌丶人生几何17 小时前
Mybatis控制台打印SQL执行信息(执行方法、执行SQL、执行时间)
java·数据库·sql·mybatis
ℳ₯㎕ddzོꦿ࿐1 天前
Spring Boot集成MyBatis-Plus:自定义拦截器实现动态表名切换
spring boot·后端·mybatis
總鑽風1 天前
解决单元测试时找不到类名
java·单元测试·mybatis