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&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'
来运行测试方法。确保数据库中有相应的表和数据。