什么是MyBatis?
MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的工作。MyBatis 可以使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
为什么选择MyBatis?
- 轻量级:MyBatis 的核心功能无需依赖任何外部依赖,这使得它在项目集成中更加灵活。
- 灵活配置:可以通过 XML 或注解配置映射文件,支持复杂关联和嵌套查询。
- 易用性:通过减少与数据库交互的代码量,提高开发效率。
- 性能:通过延迟加载、缓存等机制,提高应用性能。
MyBatis入门指南
环境搭建
- 下载:从 MyBatis 官网下载最新版本的 MyBatis 驱动和 MyBatis 核心包。
- 配置Maven:如果使用 Maven 项目,需要在 pom.xml 中添加 MyBatis 依赖。
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>最新版本号</version> </dependency> - 数据库配置:配置数据库连接信息,如 JDBC 驱动、URL、用户名和密码。
创建映射文件
- 创建 Mapper 接口:定义 Mapper 接口,声明数据库操作的方法。
public interface UserMapper { User selectById(int id); } - 编写映射文件:创建对应的映射文件(XML 格式),配置 SQL 语句和返回类型。
<mapper namespace="com.example.mapper.UserMapper"> <select id="selectById" resultType="com.example.User"> SELECT * FROM user WHERE id = #{id} </select> </mapper>
编写服务层
- 注入 Mapper:在业务层注入 Mapper 接口。
@Service public class UserService { @Autowired private UserMapper userMapper; } - 调用 Mapper 方法:通过 Mapper 接口调用数据库操作。
@Autowired public void findUserById(int id) { User user = userMapper.selectById(id); // 处理结果 }
配置 MyBatis
- 创建 MyBatis 配置文件:定义数据源、事务管理器、映射文件位置等信息。
<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/example/mapper/UserMapper.xml"/> </mappers> </configuration>
MyBatis进阶实战
动态 SQL
MyBatis 提供了强大的动态 SQL 功能,可以动态构建 SQL 语句。
- 条件判断:
<if test="name != null and name != ''"> AND name = #{name} </if> - 选择:
<select id="selectUsers" resultType="User"> SELECT <if test="Distinct != null">DISTINCT</if> id, username, password FROM users <where> <if test="name != null and name != ''"> AND name = #{name} </if> <if test="email != null and email != ''"> AND email = #{email} </if> </where> </select>
关联查询
MyBatis 支持一对一、一对多、多对多的关联查询。
- 一对一:
<resultMap id="userMap" type="User"> <id property="id" column="id"/> <result property="username" column="username"/> <result property="password" column="password"/> <association property="address" column="address_id" select="selectAddress"/> </resultMap> <select id="selectUserById" resultMap="userMap"> SELECT * FROM user WHERE id = #{id} </select> <select id="selectAddress" resultType="Address"> SELECT * FROM address WHERE id = #{id} </select>
缓存机制
MyBatis 提供了查询缓存功能,可以提高数据库操作的性能。
- 开启全局缓存:
<settings> <setting name="cacheEnabled" value="true"/> </settings> - 配置缓存策略:
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
通过以上介绍,相信你已经对 MyBatis 有了一定的了解。在实际项目中,可以根据需求灵活运用 MyBatis 的各种特性,提高开发效率。祝你学习愉快!
