MyBatis 是一个优秀的持久层框架,它消除了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的工作。MyBatis 可以使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
快速入门
1. 环境搭建
要开始使用 MyBatis,首先需要在项目中添加依赖。以下是 Maven 依赖配置:
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
</dependencies>
2. 配置文件
创建 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/mydb"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml"/>
</mappers>
</configuration>
3. Mapper 文件
创建 UserMapper.xml 文件,定义 SQL 映射:
<?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="com.example.entity.User">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
4. 接口定义
创建 UserMapper 接口:
package com.example.mapper;
public interface UserMapper {
User selectById(Integer id);
}
5. 使用 MyBatis
创建 MyBatisUtil 工具类,用于获取 SqlSessionFactory:
package com.example.util;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisUtil {
public static SqlSessionFactory getSqlSessionFactory() throws Exception {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
return new SqlSessionFactoryBuilder().build(inputStream);
}
}
在业务代码中,使用 SqlSessionFactory 创建 SqlSession,执行 SQL:
package com.example.service;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.util.MyBatisUtil;
public class UserService {
public User getUserById(Integer id) {
try (SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession()) {
UserMapper mapper = session.getMapper(UserMapper.class);
return mapper.selectById(id);
}
}
}
实战技巧
1. 使用注解进行映射
MyBatis 支持使用注解来替代 XML 映射文件。在 UserMapper 接口中,可以使用 @Select、@Result 等注解:
package com.example.mapper;
import com.example.entity.User;
import org.apache.ibatis.annotations.*;
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "name", column = "name"),
@Result(property = "age", column = "age")
})
User selectById(Integer id);
}
2. 动态 SQL
MyBatis 支持动态 SQL,可以方便地实现复杂查询。例如,根据用户名查询用户:
package com.example.mapper;
import com.example.entity.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.jdbc.SQL;
public interface UserMapper {
@SelectProvider(type = SqlProvider.class, method = "selectByUserName")
List<User> selectByUserName(@Param("userName") String userName);
class SqlProvider {
public String selectByUserName(@Param("userName") String userName) {
return new SQL() {{
SELECT("*");
FROM("user");
if (userName != null) {
WHERE("name = #{userName}");
}
}}.toString();
}
}
}
3. 分页查询
MyBatis 支持分页查询,可以使用 RowBounds 或 PageHelper 等插件实现。
package com.example.mapper;
import com.example.entity.User;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.session.RowBounds;
public interface UserMapper {
@Select("SELECT * FROM user")
@Results({
@Result(property = "id", column = "id"),
@Result(property = "name", column = "name"),
@Result(property = "age", column = "age")
})
List<User> selectAll(RowBounds rowBounds);
}
在业务代码中,使用 RowBounds 进行分页查询:
package com.example.service;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.util.MyBatisUtil;
import java.util.List;
public class UserService {
public List<User> getUsersByPage(int pageNum, int pageSize) {
try (SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession()) {
UserMapper mapper = session.getMapper(UserMapper.class);
RowBounds rowBounds = new RowBounds((pageNum - 1) * pageSize, pageSize);
return mapper.selectAll(rowBounds);
}
}
}
性能优化
1. 缓存机制
MyBatis 提供了一级缓存和二级缓存机制,可以有效地提高查询性能。
- 一级缓存:默认开启,作用域为同一个
SqlSession。 - 二级缓存:可跨
SqlSession,但需要手动开启和配置。
<configuration>
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
<cache type="org.apache.ibatis.cache.impl.PerpetualCache"/>
</configuration>
2. SQL 优化
- 避免全表扫描:尽量使用索引,避免全表扫描。
- 减少 SQL 语句执行次数:使用批处理、存储过程等。
- 优化 SQL 语句:使用合适的 SQL 语句,避免复杂的关联查询。
3. 服务器优化
- 调整数据库连接池参数:根据实际情况调整连接池参数,如连接数、最大等待时间等。
- 优化数据库索引:合理设计索引,提高查询效率。
通过以上方法,可以有效地提高 MyBatis 的性能。
总结
MyBatis 是一个功能强大的持久层框架,通过本文的介绍,相信你已经对 MyBatis 有了一定的了解。在实际项目中,合理运用 MyBatis 的特性,可以大大提高开发效率和系统性能。希望本文对你有所帮助!
