引言
MyBatis 是一个优秀的持久层框架,它消除了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的过程。MyBatis 可以使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java 对象)映射成数据库中的记录。
对于初学者来说,MyBatis 提供了一种优雅的方式来处理数据库操作,本文将带你从入门到应用,轻松掌握 MyBatis。
MyBatis 简介
1.1 什么是 MyBatis?
MyBatis 是一个半自动化的持久层框架。它对 JDBC 的数据库操作进行了封装,使得数据库操作更加简单。
1.2 MyBatis 的核心特性
- 支持自定义 SQL、存储过程以及高级映射;
- 支持自定义结果映射;
- 支持缓存机制;
- 支持动态 SQL;
- 支持自定义数据库类型处理器。
MyBatis 入门
2.1 环境搭建
- 下载 MyBatis:访问 MyBatis 官网下载 MyBatis 的 jar 包。
- 添加依赖:在项目的 pom.xml 文件中添加 MyBatis 依赖。
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
- 配置 MyBatis:在项目的 resources 目录下创建 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">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/myproject/mapper/StudentMapper.xml"/>
</mappers>
</configuration>
2.2 创建 Mapper 接口和 XML 映射文件
- 创建 Mapper 接口:定义一个接口,其中包含数据库操作的方法。
public interface StudentMapper {
List<Student> getAllStudents();
}
- 创建 XML 映射文件:在 resources 目录下创建 StudentMapper.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.myproject.mapper.StudentMapper">
<select id="getAllStudents" resultType="com.myproject.model.Student">
SELECT * FROM student
</select>
</mapper>
2.3 编写代码
public class Main {
public static void main(String[] args) throws Exception {
// 创建 SqlSessionFactory
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(new Reader(new FileReader("mybatis-config.xml")));
// 获取 SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
// 获取 Mapper
StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
// 调用 Mapper 接口方法
List<Student> students = mapper.getAllStudents();
for (Student student : students) {
System.out.println(student);
}
// 关闭 SqlSession
sqlSession.close();
}
}
MyBatis 应用
3.1 动态 SQL
MyBatis 支持动态 SQL,可以方便地实现条件查询、分页等功能。
<select id="findStudentsByCondition" resultType="com.myproject.model.Student">
SELECT * FROM student
<where>
<if test="name != null">
AND name = #{name}
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
3.2 缓存
MyBatis 支持一级缓存和二级缓存,可以提高数据库操作的效率。
3.3 扩展
MyBatis 还支持注解开发、插件开发等功能,可以满足不同场景的需求。
总结
MyBatis 是一个功能强大的持久层框架,它可以帮助开发者简化数据库操作,提高开发效率。通过本文的学习,相信你已经对 MyBatis 有了一个初步的了解。接下来,你可以通过阅读官方文档、实践项目等方式,进一步深入学习 MyBatis。
