MyBatis 是一个优秀的持久层框架,它消除了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的工作。MyBatis 可以使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs(Plain Old Java Objects,简单的 Java 对象)映射成数据库中的记录。
MyBatis 简介
MyBatis 的设计哲学是“半自动”,它允许用户在 SQL 映射文件中灵活地定义 SQL 语句,同时提供了强大的动态 SQL 功能。这使得 MyBatis 在保持灵活性的同时,也易于学习和使用。
MyBatis 的核心组件
- SqlSession:MyBatis 的核心接口,用于执行命令、获取映射、管理事务等。
- Executor:MyBatis 的执行器,负责执行 SQL 语句并返回结果。
- MappedStatement:MyBatis 的映射语句,包含 SQL 语句和参数映射。
- SqlSource:MyBatis 的 SQL 源,用于构建 SQL 语句。
- BoundSql:MyBatis 的绑定 SQL,包含 SQL 语句和参数值。
MyBatis 入门
1. 环境搭建
首先,需要添加 MyBatis 的依赖到项目中。以下是 Maven 依赖配置:
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
</dependencies>
2. 配置文件
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>
<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/mydatabase"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml"/>
</mappers>
</configuration>
3. 映射文件
映射文件定义了 SQL 语句和参数映射。以下是一个简单的 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">
<select id="selectUser" resultType="User">
SELECT * FROM users WHERE id = #{id}
</select>
</mapper>
4. 接口
MyBatis 使用接口来定义 SQL 映射。以下是一个简单的 UserMapper 接口示例:
package com.example.mapper;
import com.example.entity.User;
public interface UserMapper {
User selectUser(Integer id);
}
MyBatis 进阶
动态 SQL
MyBatis 支持动态 SQL,可以灵活地构建 SQL 语句。以下是一个使用 <if> 标签的动态 SQL 示例:
<select id="selectUsers" resultType="User">
SELECT * FROM users
<where>
<if test="name != null">
AND name = #{name}
</if>
<if test="email != null">
AND email = #{email}
</if>
</where>
</select>
类型处理器
MyBatis 支持自定义类型处理器,用于将 Java 类型转换为数据库类型。以下是一个简单的类型处理器示例:
package com.example.typehandler;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserStatusTypeHandler extends BaseTypeHandler<String> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, parameter);
}
@Override
public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
return rs.getString(columnName);
}
@Override
public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return rs.getString(columnIndex);
}
@Override
public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return cs.getString(columnIndex);
}
}
插件
MyBatis 插件允许用户扩展 MyBatis 的功能。以下是一个简单的插件示例:
package com.example.plugin;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.plugin.*;
import java.sql.Connection;
import java.util.Properties;
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class})})
public class MyPlugin implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
// 在这里可以修改 SQL 语句
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
// 设置插件属性
}
}
MyBatis 实战案例解析
1. 用户管理模块
以下是一个简单的用户管理模块的 MyBatis 映射文件和接口示例:
<!-- UserMapper.xml -->
<mapper namespace="com.example.mapper.UserMapper">
<insert id="insertUser" parameterType="User">
INSERT INTO users (name, email) VALUES (#{name}, #{email})
</insert>
<update id="updateUser" parameterType="User">
UPDATE users SET name = #{name}, email = #{email} WHERE id = #{id}
</update>
<delete id="deleteUser" parameterType="Integer">
DELETE FROM users WHERE id = #{id}
</delete>
<select id="selectUser" resultType="User">
SELECT * FROM users WHERE id = #{id}
</select>
</mapper>
<!-- UserMapper.java -->
package com.example.mapper;
import com.example.entity.User;
public interface UserMapper {
void insertUser(User user);
void updateUser(User user);
void deleteUser(Integer id);
User selectUser(Integer id);
}
2. 商品管理模块
以下是一个简单的商品管理模块的 MyBatis 映射文件和接口示例:
<!-- ProductMapper.xml -->
<mapper namespace="com.example.mapper.ProductMapper">
<insert id="insertProduct" parameterType="Product">
INSERT INTO products (name, price) VALUES (#{name}, #{price})
</insert>
<update id="updateProduct" parameterType="Product">
UPDATE products SET name = #{name}, price = #{price} WHERE id = #{id}
</update>
<delete id="deleteProduct" parameterType="Integer">
DELETE FROM products WHERE id = #{id}
</delete>
<select id="selectProduct" resultType="Product">
SELECT * FROM products WHERE id = #{id}
</select>
</mapper>
<!-- ProductMapper.java -->
package com.example.mapper;
import com.example.entity.Product;
public interface ProductMapper {
void insertProduct(Product product);
void updateProduct(Product product);
void deleteProduct(Integer id);
Product selectProduct(Integer id);
}
MyBatis 最佳实践
1. 遵循“约定大于配置”的原则
MyBatis 提供了许多默认值和约定,例如映射文件和接口的命名规范。尽量遵循这些约定,以减少配置。
2. 使用注解和 XML 配置
根据项目需求,选择使用注解或 XML 配置。注解简洁易读,XML 配置灵活性强。
3. 使用动态 SQL
动态 SQL 可以灵活地构建 SQL 语句,但需要注意性能问题。
4. 使用缓存
MyBatis 支持一级缓存和二级缓存。合理使用缓存可以提高性能。
5. 模块化设计
将 MyBatis 映射文件和接口分散到不同的模块中,提高代码可维护性。
6. 单元测试
编写单元测试,确保 MyBatis 映射文件和接口的正确性。
通过以上内容,相信你已经对 MyBatis 有了一定的了解。希望这篇文章能帮助你更好地掌握 MyBatis,并将其应用到实际项目中。
