龙岗营销网站建设公司哪家好,雄安智能网站建设,深圳建筑工地招聘信息,最好看免费中文基础知识
MyBatis 是一款优秀的持久层框架#xff0c;其核心组件主要包括以下部分#xff1a;
SqlSession 作用#xff1a;SqlSession 是 MyBatis 的核心接口#xff0c;负责与数据库进行通信#xff0c;执行 SQL 语句#xff0c;并返回查询结果。它是 MyBatis 的一次会… 基础知识
MyBatis 是一款优秀的持久层框架其核心组件主要包括以下部分
SqlSession 作用SqlSession 是 MyBatis 的核心接口负责与数据库进行通信执行 SQL 语句并返回查询结果。它是 MyBatis 的一次会话可以执行多个 SQL 语句。 功能提供了执行 SQL 语句、获取映射器Mapper、管理事务等功能。通过 SqlSession可以执行数据库的增删改查操作并获取操作结果。
Executor 作用Executor 是 MyBatis 用来执行 SQL 语句的接口是 MyBatis 框架中所有数据库操作的核心。 类型MyBatis 提供了几种不同类型的 Executor 实现如 SimpleExecutor、ReuseExecutor 和 BatchExecutor分别适用于不同的应用场景。
Mapper接口 作用Mapper 接口是 MyBatis 实现 ORM 映射的核心机制。用户可以通过定义接口来描述数据库表结构并使用注解或 XML 配置文件指定 SQL 语句。 功能当调用 Mapper 接口的方法时MyBatis 会利用动态代理技术拦截这些调用并根据方法签名生成对应的 statementId。随后MyBatis 会查找预编译好的 SQL 语句并执行相应的数据库操作。
Configuration 作用Configuration 类是 MyBatis 所有配置信息的封装。它包含了 MyBatis 运行时所需的所有配置如数据库连接信息DataSource、事务管理器TransactionManager、类型处理器TypeHandlers、映射器Mapper的注册信息等。 功能提供了框架的全局配置信息使得 MyBatis 能够根据这些配置完成初始化和功能扩展。
MappedStatement 作用MappedStatement 是 MyBatis 中最重要的一个类它封装了 SQL 语句的所有信息包括 SQL 语句本身、输入参数的类型、返回结果的类型、是否使用缓存等。 功能在 MyBatis 中每一个 select、insert、update、delete 标签都会被解析成一个 MappedStatement 对象并存储在 Configuration 对象中。
ParameterHandler 作用ParameterHandler 是 MyBatis 中用于处理 SQL 语句参数的接口。它负责将用户传递的参数值设置到 SQL 语句的占位符中。 功能通过与 TypeHandler 的协作将 Java 类型的参数转换为 JDBC 类型的参数并设置到 PreparedStatement 的相应位置。
TypeHandler 作用TypeHandler 是 MyBatis 中用于处理 Java 类型和 JDBC 类型之间转换的接口。 功能定义了如何将 Java 类型转换为 JDBC 类型用于设置 SQL 语句的参数以及如何将 JDBC 类型转换为 Java 类型用于从结果集中获取数据。
ResultSetHandler 作用ResultSetHandler 是 MyBatis 中用于处理 SQL 查询结果集的接口。它负责将 JDBC 的 ResultSet 转换为 Java 对象或集合。 功能通过与 TypeHandler 的协作从 ResultSet 中读取数据并将其转换为 Java 类型的值。然后它根据 Mapper 接口方法的返回类型将这些值组装成相应的 Java 对象或集合。
StatementHandler 作用StatementHandler 是 MyBatis 中用于处理 SQL 语句的执行的接口。它封装了 JDBC 的 Statement 或 PreparedStatement并提供了执行 SQL 语句的方法。 功能负责配置 SQL 语句的参数、执行 SQL 语句并处理执行过程中可能出现的异常。
如何快速上手 MyBatis 搭建开发环境 引入 MyBatis 依赖在项目的 pom.xml 文件中添加 MyBatis 的 Maven 依赖。 配置数据库连接创建 mybatis-config.xml 配置文件配置数据库连接信息、事务管理器、类型处理器等。 创建 SqlSessionFactory 使用 SqlSessionFactoryBuilder 创建 SqlSessionFactory 实例加载 mybatis-config.xml 配置文件。 获取 SqlSession 通过 SqlSessionFactory.openSession() 方法获取 SqlSession 实例用于执行数据库操作。 定义 Mapper 接口 创建 Mapper 接口定义数据库操作的方法如 selectById、insert 等。 编写 Mapper XML 文件 创建与 Mapper 接口对应的 XML 文件编写 SQL 语句如 select、insert 等标签。 执行数据库操作 通过 SqlSession 获取 Mapper 接口的实例调用其方法执行数据库操作。 关闭资源 操作完成后调用 SqlSession.close() 方法关闭会话释放资源。 参考案例
1. 数据库准备
首先创建一个简单的数据库表 Student包含以下字段
CREATE TABLE Student (id INT PRIMARY KEY AUTO_INCREMENT,name VARCHAR(50) NOT NULL,age INT NOT NULL
);
2. MyBatis 核心组件用途示例
结合一个简单的 Java 应用展示 MyBatis 的核心组件是如何协同工作的。
核心组件 SqlSessionFactory负责创建 SqlSession。 SqlSession负责执行 SQL、提交或回滚事务。 Mapper接口定义数据库操作的接口。 Mapper XML文件编写 SQL 语句。 ConfigurationMyBatis 的全局配置文件。 MappedStatement存储 SQL 信息。
3. 代码案例
3.1 Maven 依赖
确保在 pom.xml 中添加 MyBatis 和 MySQL 的依赖
dependenciesdependencygroupIdorg.mybatis/groupIdartifactIdmybatis/artifactIdversion3.5.13/version/dependencydependencygroupIdmysql/groupIdartifactIdmysql-connector-java/artifactIdversion8.0.31/version/dependencydependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactIdversion1.18.24/version/dependency
/dependencies
3.2 数据库配置文件db.properties
drivercom.mysql.cj.jdbc.Driver
urljdbc:mysql://localhost:3306/test?useSSLfalseserverTimezoneUTC
usernameroot
password123456
3.3 MyBatis 全局配置文件mybatis-config.xml
?xml version1.0 encodingUTF-8 ?
!DOCTYPE configurationPUBLIC -//mybatis.org//DTD Config 3.0//ENhttp://mybatis.org/dtd/mybatis-3-config.dtd
configurationenvironments defaultdevelopmentenvironment iddevelopmenttransactionManager typeJDBC/dataSource typePOOLEDproperty namedriver value${driver}/property nameurl value${url}/property nameusername value${username}/property namepassword value${password}//dataSource/environment/environmentsmappersmapper resourcemapper/StudentMapper.xml//mappers
/configuration
3.4 Student 实体类
import lombok.Data;Data
public class Student {private Integer id;private String name;private Integer age;
}
3.5 StudentMapper 接口
import org.apache.ibatis.annotations.Mapper;import java.util.List;Mapper
public interface StudentMapper {ListStudent getAllStudents();void insertStudent(Student student);Student getStudentById(Integer id);void updateStudent(Student student);void deleteStudentById(Integer id);
}
3.6 StudentMapper.xml 文件
?xml version1.0 encodingUTF-8 ?
!DOCTYPE mapperPUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttp://mybatis.org/dtd/mybatis-3-mapper.dtd
mapper namespacecom.example.mapper.StudentMapperselect idgetAllStudents resultTypecom.example.model.StudentSELECT * FROM Student/selectinsert idinsertStudent parameterTypecom.example.model.StudentINSERT INTO Student (name, age) VALUES (#{name}, #{age})/insertselect idgetStudentById parameterTypeint resultTypecom.example.model.StudentSELECT * FROM Student WHERE id #{id}/selectupdate idupdateStudent parameterTypecom.example.model.StudentUPDATE Student SET name #{name}, age #{age} WHERE id #{id}/updatedelete iddeleteStudentById parameterTypeintDELETE FROM Student WHERE id #{id}/delete
/mapper
3.7 工具类获取 SqlSession
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 java.io.IOException;
import java.io.InputStream;public class MyBatisUtils {private static SqlSessionFactory sqlSessionFactory;static {try {String resource mybatis-config.xml;InputStream inputStream Resources.getResourceAsStream(resource);sqlSessionFactory new SqlSessionFactoryBuilder().build(inputStream);} catch (IOException e) {e.printStackTrace();}}public static SqlSession getSqlSession() {return sqlSessionFactory.openSession();}
}
3.8 测试代码
import com.example.mapper.StudentMapper;
import com.example.model.Student;public class Main {public static void main(String[] args) {// 获取 SqlSession 实例SqlSession sqlSession MyBatisUtils.getSqlSession();try {// 获取 Mapper 接口StudentMapper studentMapper sqlSession.getMapper(StudentMapper.class);// 插入一条数据Student student new Student();student.setName(张三);student.setAge(20);studentMapper.insertStudent(student);sqlSession.commit(); // 提交事务// 查询所有学生ListStudent students studentMapper.getAllStudents();for (Student s : students) {System.out.println(s);}// 查询单个学生Student studentById studentMapper.getStudentById(1);System.out.println(studentById);// 更新学生信息studentById.setName(李四);studentById.setAge(22);studentMapper.updateStudent(studentById);sqlSession.commit();// 删除学生studentMapper.deleteStudentById(1);sqlSession.commit();} finally {// 关闭 SqlSessionsqlSession.close();}}
}
4. 核心组件总结 SqlSessionFactory通过配置文件加载全局配置信息。 SqlSession负责执行 SQL、提交或回滚事务。 Mapper接口抽象了数据库操作。 Mapper XML实际的 SQL 语句。 ConfigurationMyBatis 的全局配置文件。 MappedStatement存储 SQL 信息如 getAllStudents。