SSM从入门到实战:2.1 MyBatis框架概述与环境搭建
👋 大家好,我是 阿问学长
!专注于分享优质开源项目
解析、毕业设计项目指导
支持、幼小初高
的教辅资料
推荐等,欢迎关注交流!🚀
08-MyBatis框架概述与环境搭建
📖 本文概述
本文是SSM框架系列MyBatis基础篇的第一篇,将全面介绍MyBatis框架的基本概念、核心特性和环境搭建。通过详细的配置示例和入门案例,帮助读者快速掌握MyBatis的基础知识。
🎯 学习目标
- 深入理解MyBatis框架的概念和特点
- 掌握MyBatis的核心组件和工作原理
- 学会搭建MyBatis开发环境
- 完成第一个MyBatis程序
- 了解MyBatis与其他ORM框架的区别
1. MyBatis框架概述
1.1 什么是MyBatis
/*** MyBatis框架概述*/
public class MyBatisOverview {/*** MyBatis是什么?* * MyBatis是一款优秀的持久层框架,它支持自定义SQL、存储过程以及高级映射。* MyBatis免除了几乎所有的JDBC代码以及设置参数和获取结果集的工作。* MyBatis可以通过简单的XML或注解来配置和映射原始类型、接口和Java POJO* (Plain Old Java Objects,普通老式Java对象)为数据库中的记录。*//*** MyBatis的前身* * MyBatis原名iBatis,是Apache的一个开源项目。* 2010年这个项目由Apache Software Foundation迁移到了Google Code,* 并且改名为MyBatis。2013年11月迁移到Github。*//*** MyBatis的特点:* * 1. 简单易学:本身就很小且简单* 2. 灵活:不会对应用程序或者数据库的现有设计强加任何影响* 3. 解除SQL与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离* 4. 提供映射标签:支持对象与数据库的ORM字段关系映射* 5. 提供对象关系映射标签:支持对象关系组建维护* 6. 提供XML标签:支持编写动态SQL*/
}
1.2 MyBatis vs 其他ORM框架
/*** MyBatis与其他ORM框架对比*/
public class ORMComparison {/*** MyBatis vs Hibernate*/public void myBatisVsHibernate() {/** MyBatis优势:* 1. SQL可控性强,可以进行SQL优化* 2. 学习成本低,容易上手* 3. 对复杂查询支持更好* 4. 对存储过程支持更好* 5. 可以使用原生SQL* * Hibernate优势:* 1. 完全面向对象,开发效率高* 2. 数据库无关性好* 3. 缓存机制更完善* 4. 对象关系映射更强大* 5. 自动生成SQL*/}/*** MyBatis vs JPA*/public void myBatisVsJPA() {/** MyBatis优势:* 1. SQL控制更灵活* 2. 性能调优更容易* 3. 对复杂查询支持更好* 4. 学习曲线更平缓* * JPA优势:* 1. 标准化,可移植性好* 2. 面向对象程度更高* 3. 代码量更少* 4. 自动化程度更高*/}/*** MyBatis vs Spring Data JPA*/public void myBatisVsSpringDataJPA() {/** MyBatis优势:* 1. SQL完全可控* 2. 复杂查询更容易实现* 3. 性能优化空间大* 4. 对遗留系统支持更好* * Spring Data JPA优势:* 1. 开发效率极高* 2. 代码量极少* 3. 方法名查询很方便* 4. 与Spring生态集成更好*/}
}
1.3 MyBatis核心组件
/*** MyBatis核心组件介绍*/
public class MyBatisCoreComponents {/*** 1. SqlSessionFactory* SqlSession工厂,用于创建SqlSession实例*/private SqlSessionFactory sqlSessionFactory;/*** 2. SqlSession* 执行SQL命令的主要接口,包含了面向数据库执行SQL命令所需的所有方法*/private SqlSession sqlSession;/*** 3. Mapper接口* 定义数据访问方法的接口*/public interface UserMapper {User selectById(Long id);List<User> selectAll();int insert(User user);int update(User user);int delete(Long id);}/*** 4. Mapper 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="com.example.mapper.UserMapper"><select id="selectById" resultType="User">SELECT * FROM users WHERE id = #{id}</select></mapper>*//*** 5. Configuration* MyBatis的配置信息,包含数据源、事务管理器、映射器等*/private Configuration configuration;/*** MyBatis工作流程:* * 1. 读取配置文件,创建SqlSessionFactory* 2. 通过SqlSessionFactory创建SqlSession* 3. 通过SqlSession获取Mapper接口的代理对象* 4. 调用Mapper接口方法执行SQL* 5. SqlSession提交事务并关闭*/public void workFlow() {// 1. 创建SqlSessionFactorySqlSessionFactory factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("mybatis-config.xml"));// 2. 创建SqlSessionSqlSession session = factory.openSession();try {// 3. 获取MapperUserMapper mapper = session.getMapper(UserMapper.class);// 4. 执行SQLUser user = mapper.selectById(1L);// 5. 提交事务session.commit();} finally {// 6. 关闭SqlSessionsession.close();}}
}
2. 环境搭建
2.1 Maven依赖配置
<!-- pom.xml文件配置 -->
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.example</groupId><artifactId>mybatis-demo</artifactId><version>1.0.0</version><packaging>jar</packaging><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><!-- 版本管理 --><mybatis.version>3.5.13</mybatis.version><mysql.version>8.0.33</mysql.version><junit.version>4.13.2</junit.version><logback.version>1.2.12</logback.version></properties><dependencies><!-- MyBatis核心依赖 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>${mybatis.version}</version></dependency><!-- MySQL驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>${mysql.version}</version></dependency><!-- 日志依赖 --><dependency><groupId>ch.qos.logback</groupId><artifactId>logback-classic</artifactId><version>${logback.version}</version></dependency><!-- 测试依赖 --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>${junit.version}</version><scope>test</scope></dependency><!-- 连接池(可选) --><dependency><groupId>com.zaxxer</groupId><artifactId>HikariCP</artifactId><version>4.0.3</version></dependency></dependencies><build><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.8.1</version><configuration><source>8</source><target>8</target></configuration></plugin></plugins><!-- 资源文件配置 --><resources><resource><directory>src/main/resources</directory><includes><include>**/*.xml</include><include>**/*.properties</include></includes></resource><resource><directory>src/main/java</directory><includes><include>**/*.xml</include></includes></resource></resources></build>
</project>
2.2 数据库准备
-- 创建数据库
CREATE DATABASE mybatis_demo DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;USE mybatis_demo;-- 创建用户表
CREATE TABLE users (id BIGINT PRIMARY KEY AUTO_INCREMENT,username VARCHAR(50) NOT NULL UNIQUE,email VARCHAR(100) NOT NULL UNIQUE,password VARCHAR(100) NOT NULL,age INT,status TINYINT DEFAULT 1 COMMENT '1:正常 0:禁用',create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);-- 插入测试数据
INSERT INTO users (username, email, password, age) VALUES
('admin', 'admin@example.com', 'admin123', 25),
('user1', 'user1@example.com', 'user123', 30),
('user2', 'user2@example.com', 'user456', 28);-- 创建角色表
CREATE TABLE roles (id BIGINT PRIMARY KEY AUTO_INCREMENT,role_name VARCHAR(50) NOT NULL UNIQUE,description VARCHAR(200),create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);-- 插入角色数据
INSERT INTO roles (role_name, description) VALUES
('ADMIN', '管理员'),
('USER', '普通用户'),
('GUEST', '访客');-- 创建用户角色关联表
CREATE TABLE user_roles (id BIGINT PRIMARY KEY AUTO_INCREMENT,user_id BIGINT NOT NULL,role_id BIGINT NOT NULL,create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE,UNIQUE KEY uk_user_role (user_id, role_id)
);-- 插入用户角色关联数据
INSERT INTO user_roles (user_id, role_id) VALUES
(1, 1), -- admin用户拥有ADMIN角色
(2, 2), -- user1用户拥有USER角色
(3, 2); -- user2用户拥有USER角色
2.3 MyBatis配置文件
<!-- src/main/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><!-- 属性配置 --><properties resource="database.properties"/><!-- 设置 --><settings><!-- 开启驼峰命名自动映射 --><setting name="mapUnderscoreToCamelCase" value="true"/><!-- 开启延迟加载 --><setting name="lazyLoadingEnabled" value="true"/><!-- 设置超时时间 --><setting name="defaultStatementTimeout" value="30"/><!-- 开启二级缓存 --><setting name="cacheEnabled" value="true"/><!-- 日志实现 --><setting name="logImpl" value="SLF4J"/></settings><!-- 类型别名 --><typeAliases><typeAlias type="com.example.entity.User" alias="User"/><typeAlias type="com.example.entity.Role" alias="Role"/><!-- 或者使用包扫描 --><!-- <package name="com.example.entity"/> --></typeAliases><!-- 类型处理器 --><typeHandlers><!-- 自定义类型处理器 --><!-- <typeHandler handler="com.example.handler.CustomTypeHandler"/> --></typeHandlers><!-- 环境配置 --><environments default="development"><environment id="development"><!-- 事务管理器 --><transactionManager type="JDBC"/><!-- 数据源 --><dataSource type="POOLED"><property name="driver" value="${database.driver}"/><property name="url" value="${database.url}"/><property name="username" value="${database.username}"/><property name="password" value="${database.password}"/><!-- 连接池配置 --><property name="poolMaximumActiveConnections" value="20"/><property name="poolMaximumIdleConnections" value="5"/><property name="poolMaximumCheckoutTime" value="20000"/><property name="poolTimeToWait" value="20000"/></dataSource></environment><!-- 测试环境 --><environment id="test"><transactionManager type="JDBC"/><dataSource type="POOLED"><property name="driver" value="org.h2.Driver"/><property name="url" value="jdbc:h2:mem:testdb"/><property name="username" value="sa"/><property name="password" value=""/></dataSource></environment></environments><!-- 映射器 --><mappers><!-- 单个映射器注册 --><mapper resource="mapper/UserMapper.xml"/><mapper resource="mapper/RoleMapper.xml"/><!-- 或者使用包扫描 --><!-- <package name="com.example.mapper"/> --><!-- 或者使用类注册 --><!-- <mapper class="com.example.mapper.UserMapper"/> --></mappers></configuration>
2.4 数据库配置文件
# src/main/resources/database.properties# 数据库连接配置
database.driver=com.mysql.cj.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/mybatis_demo?useSSL=false&serverTimezone=UTC&characterEncoding=utf8
database.username=root
database.password=123456# 连接池配置
database.initialSize=5
database.maxActive=20
database.maxIdle=10
database.minIdle=5
database.maxWait=60000
2.5 日志配置
<!-- src/main/resources/logback.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<configuration><!-- 控制台输出 --><appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"><encoder><pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern></encoder></appender><!-- 文件输出 --><appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"><file>logs/mybatis-demo.log</file><rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"><fileNamePattern>logs/mybatis-demo.%d{yyyy-MM-dd}.log</fileNamePattern><maxHistory>30</maxHistory></rollingPolicy><encoder><pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern></encoder></appender><!-- MyBatis SQL日志 --><logger name="com.example.mapper" level="DEBUG"/><!-- 根日志级别 --><root level="INFO"><appender-ref ref="CONSOLE"/><appender-ref ref="FILE"/></root></configuration>
3. 实体类设计
3.1 用户实体类
/*** 用户实体类*/
package com.example.entity;import java.time.LocalDateTime;
import java.util.List;public class User {private Long id;private String username;private String email;private String password;private Integer age;private Integer status;private LocalDateTime createTime;private LocalDateTime updateTime;// 关联属性private List<Role> roles;// 构造方法public User() {}public User(String username, String email, String password) {this.username = username;this.email = email;this.password = password;}public User(String username, String email, String password, Integer age) {this.username = username;this.email = email;this.password = password;this.age = age;}// Getter和Setter方法public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Integer getStatus() {return status;}public void setStatus(Integer status) {this.status = status;}public LocalDateTime getCreateTime() {return createTime;}public void setCreateTime(LocalDateTime createTime) {this.createTime = createTime;}public LocalDateTime getUpdateTime() {return updateTime;}public void setUpdateTime(LocalDateTime updateTime) {this.updateTime = updateTime;}public List<Role> getRoles() {return roles;}public void setRoles(List<Role> roles) {this.roles = roles;}// toString方法@Overridepublic String toString() {return "User{" +"id=" + id +", username='" + username + '\'' +", email='" + email + '\'' +", age=" + age +", status=" + status +", createTime=" + createTime +", updateTime=" + updateTime +'}';}// equals和hashCode方法@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;User user = (User) o;return id != null ? id.equals(user.id) : user.id == null;}@Overridepublic int hashCode() {return id != null ? id.hashCode() : 0;}
}
3.2 角色实体类
/*** 角色实体类*/
package com.example.entity;import java.time.LocalDateTime;
import java.util.List;public class Role {private Long id;private String roleName;private String description;private LocalDateTime createTime;// 关联属性private List<User> users;// 构造方法public Role() {}public Role(String roleName, String description) {this.roleName = roleName;this.description = description;}// Getter和Setter方法public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getRoleName() {return roleName;}public void setRoleName(String roleName) {this.roleName = roleName;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}public LocalDateTime getCreateTime() {return createTime;}public void setCreateTime(LocalDateTime createTime) {this.createTime = createTime;}public List<User> getUsers() {return users;}public void setUsers(List<User> users) {this.users = users;}// toString方法@Overridepublic String toString() {return "Role{" +"id=" + id +", roleName='" + roleName + '\'' +", description='" + description + '\'' +", createTime=" + createTime +'}';}// equals和hashCode方法@Overridepublic boolean equals(Object o) {if (this == o) return true;if (o == null || getClass() != o.getClass()) return false;Role role = (Role) o;return id != null ? id.equals(role.id) : role.id == null;}@Overridepublic int hashCode() {return id != null ? id.hashCode() : 0;}
}
4. 第一个MyBatis程序
4.1 Mapper接口
/*** 用户Mapper接口*/
package com.example.mapper;import com.example.entity.User;
import java.util.List;public interface UserMapper {/*** 根据ID查询用户*/User selectById(Long id);/*** 查询所有用户*/List<User> selectAll();/*** 根据用户名查询用户*/User selectByUsername(String username);/*** 插入用户*/int insert(User user);/*** 更新用户*/int update(User user);/*** 删除用户*/int deleteById(Long id);/*** 统计用户数量*/long count();
}
4.2 Mapper XML文件
<!-- src/main/resources/mapper/UserMapper.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.example.mapper.UserMapper"><!-- 结果映射 --><resultMap id="UserResultMap" type="User"><id property="id" column="id"/><result property="username" column="username"/><result property="email" column="email"/><result property="password" column="password"/><result property="age" column="age"/><result property="status" column="status"/><result property="createTime" column="create_time"/><result property="updateTime" column="update_time"/></resultMap><!-- 基础SQL片段 --><sql id="Base_Column_List">id, username, email, password, age, status, create_time, update_time</sql><!-- 根据ID查询用户 --><select id="selectById" parameterType="long" resultMap="UserResultMap">SELECT <include refid="Base_Column_List"/>FROM usersWHERE id = #{id}</select><!-- 查询所有用户 --><select id="selectAll" resultMap="UserResultMap">SELECT <include refid="Base_Column_List"/>FROM usersORDER BY id</select><!-- 根据用户名查询用户 --><select id="selectByUsername" parameterType="string" resultMap="UserResultMap">SELECT <include refid="Base_Column_List"/>FROM usersWHERE username = #{username}</select><!-- 插入用户 --><insert id="insert" parameterType="User" useGeneratedKeys="true" keyProperty="id">INSERT INTO users (username, email, password, age, status)VALUES (#{username}, #{email}, #{password}, #{age}, #{status})</insert><!-- 更新用户 --><update id="update" parameterType="User">UPDATE usersSET username = #{username},email = #{email},password = #{password},age = #{age},status = #{status},update_time = CURRENT_TIMESTAMPWHERE id = #{id}</update><!-- 删除用户 --><delete id="deleteById" parameterType="long">DELETE FROM users WHERE id = #{id}</delete><!-- 统计用户数量 --><select id="count" resultType="long">SELECT COUNT(*) FROM users</select></mapper>
4.3 测试程序
/*** MyBatis测试程序*/
package com.example.test;import com.example.entity.User;
import com.example.mapper.UserMapper;
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.junit.After;
import org.junit.Before;
import org.junit.Test;import java.io.IOException;
import java.io.InputStream;
import java.util.List;public class MyBatisTest {private SqlSessionFactory sqlSessionFactory;private SqlSession sqlSession;private UserMapper userMapper;@Beforepublic void setUp() throws IOException {// 读取配置文件InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");// 创建SqlSessionFactorysqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);// 创建SqlSessionsqlSession = sqlSessionFactory.openSession();// 获取MapperuserMapper = sqlSession.getMapper(UserMapper.class);}@Afterpublic void tearDown() {if (sqlSession != null) {sqlSession.close();}}@Testpublic void testSelectById() {User user = userMapper.selectById(1L);System.out.println("查询结果: " + user);}@Testpublic void testSelectAll() {List<User> users = userMapper.selectAll();System.out.println("用户总数: " + users.size());for (User user : users) {System.out.println(user);}}@Testpublic void testInsert() {User user = new User("testuser", "test@example.com", "test123", 25);user.setStatus(1);int result = userMapper.insert(user);sqlSession.commit(); // 提交事务System.out.println("插入结果: " + result);System.out.println("生成的ID: " + user.getId());}@Testpublic void testUpdate() {User user = userMapper.selectById(1L);if (user != null) {user.setAge(30);user.setEmail("updated@example.com");int result = userMapper.update(user);sqlSession.commit(); // 提交事务System.out.println("更新结果: " + result);}}@Testpublic void testDelete() {int result = userMapper.deleteById(3L);sqlSession.commit(); // 提交事务System.out.println("删除结果: " + result);}@Testpublic void testCount() {long count = userMapper.count();System.out.println("用户总数: " + count);}@Testpublic void testSelectByUsername() {User user = userMapper.selectByUsername("admin");System.out.println("查询结果: " + user);}
}
5. 工具类封装
5.1 MyBatis工具类
/*** MyBatis工具类*/
package com.example.util;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 {// 读取配置文件InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");// 创建SqlSessionFactorysqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);} catch (IOException e) {throw new RuntimeException("初始化MyBatis失败", e);}}/*** 获取SqlSessionFactory*/public static SqlSessionFactory getSqlSessionFactory() {return sqlSessionFactory;}/*** 获取SqlSession*/public static SqlSession getSqlSession() {return sqlSessionFactory.openSession();}/*** 获取自动提交的SqlSession*/public static SqlSession getSqlSession(boolean autoCommit) {return sqlSessionFactory.openSession(autoCommit);}/*** 获取Mapper*/public static <T> T getMapper(Class<T> mapperClass) {SqlSession sqlSession = getSqlSession();return sqlSession.getMapper(mapperClass);}/*** 执行操作并自动管理SqlSession*/public static <T> T execute(SqlSessionCallback<T> callback) {SqlSession sqlSession = getSqlSession();try {T result = callback.doInSqlSession(sqlSession);sqlSession.commit();return result;} catch (Exception e) {sqlSession.rollback();throw new RuntimeException("执行数据库操作失败", e);} finally {sqlSession.close();}}/*** SqlSession回调接口*/public interface SqlSessionCallback<T> {T doInSqlSession(SqlSession sqlSession);}
}
5.2 使用工具类的示例
/*** 使用工具类的DAO实现*/
package com.example.dao;import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.util.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;import java.util.List;public class UserDao {/*** 根据ID查询用户*/public User selectById(Long id) {return MyBatisUtils.execute(sqlSession -> {UserMapper mapper = sqlSession.getMapper(UserMapper.class);return mapper.selectById(id);});}/*** 查询所有用户*/public List<User> selectAll() {return MyBatisUtils.execute(sqlSession -> {UserMapper mapper = sqlSession.getMapper(UserMapper.class);return mapper.selectAll();});}/*** 插入用户*/public int insert(User user) {return MyBatisUtils.execute(sqlSession -> {UserMapper mapper = sqlSession.getMapper(UserMapper.class);return mapper.insert(user);});}/*** 更新用户*/public int update(User user) {return MyBatisUtils.execute(sqlSession -> {UserMapper mapper = sqlSession.getMapper(UserMapper.class);return mapper.update(user);});}/*** 删除用户*/public int deleteById(Long id) {return MyBatisUtils.execute(sqlSession -> {UserMapper mapper = sqlSession.getMapper(UserMapper.class);return mapper.deleteById(id);});}/*** 手动管理SqlSession的示例*/public User selectByIdManual(Long id) {SqlSession sqlSession = MyBatisUtils.getSqlSession();try {UserMapper mapper = sqlSession.getMapper(UserMapper.class);return mapper.selectById(id);} finally {sqlSession.close();}}
}
6. 小结
本文全面介绍了MyBatis框架的基础知识:
- 框架概述:MyBatis的特点和与其他ORM框架的对比
- 核心组件:SqlSessionFactory、SqlSession、Mapper等核心组件
- 环境搭建:Maven依赖、数据库准备、配置文件等
- 实体设计:用户和角色实体类的设计
- 第一个程序:完整的MyBatis程序示例
- 工具封装:MyBatis工具类的设计和使用
掌握MyBatis基础的关键点:
- 理解MyBatis的工作原理和核心组件
- 正确配置MyBatis环境和数据库连接
- 熟练编写Mapper接口和XML映射文件
- 掌握基本的CRUD操作
- 学会使用工具类简化开发
🔗 下一篇预告
下一篇文章将介绍MyBatis基本操作与映射配置,深入学习MyBatis的映射配置和各种操作技巧。
相关文章:
- 下一篇:MyBatis基本操作与映射配置
- 返回目录