MyBatis简介
MyBatis是一个优秀的持久层框架,它消除了几乎所有的JDBC代码和手动设置参数以及获取结果集的工作。MyBatis通过简单的XML或注解用于配置和原始映射,将接口和Java的POJOs(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。
入门篇
1. 环境搭建
1.1 安装Java开发环境
首先,确保你的电脑上安装了Java开发环境,包括JDK和Java环境变量配置。
1.2 安装IDE
推荐使用IntelliJ IDEA或Eclipse等IDE进行开发,这些IDE提供了MyBatis的插件,可以方便地使用MyBatis。
1.3 添加MyBatis依赖
在项目的pom.xml文件中添加以下依赖:
<dependencies>
<!-- MyBatis依赖 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<!-- 数据库驱动依赖,根据实际数据库选择 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</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.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/your_database"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/your/package/mapper/YourMapper.xml"/>
</mappers>
</configuration>
3. 编写Mapper接口
在相应的包下创建一个Mapper接口,例如YourMapper.java。
package com.your.package.mapper;
import java.util.List;
public interface YourMapper {
List<YourEntity> selectAll();
}
4. 编写Mapper XML
在src/main/resources目录下创建一个名为YourMapper.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.your.package.mapper.YourMapper">
<select id="selectAll" resultType="com.your.package.entity.YourEntity">
SELECT * FROM your_table
</select>
</mapper>
进阶篇
1. 动态SQL
MyBatis支持动态SQL,可以通过<if>、<choose>、<when>、<otherwise>等标签实现。
<select id="selectByCondition" resultType="com.your.package.entity.YourEntity">
SELECT * FROM your_table
<where>
<if test="name != null">
AND name = #{name}
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
2. 一对一、一对多关联
MyBatis支持一对一、一对多关联查询。
1. 一对一
<resultMap id="YourEntityResultMap" type="com.your.package.entity.YourEntity">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="age" property="age"/>
<association property="address" column="address_id" select="selectAddress"/>
</resultMap>
<select id="selectYourEntity" resultMap="YourEntityResultMap">
SELECT * FROM your_table WHERE id = #{id}
</select>
<select id="selectAddress" resultType="com.your.package.entity.Address">
SELECT * FROM address WHERE id = #{id}
</select>
2. 一对多
<resultMap id="YourEntityResultMap" type="com.your.package.entity.YourEntity">
<id column="id" property="id"/>
<result column="name" property="name"/>
<result column="age" property="age"/>
<collection property="orders" column="id" select="selectOrders"/>
</resultMap>
<select id="selectYourEntity" resultMap="YourEntityResultMap">
SELECT * FROM your_table WHERE id = #{id}
</select>
<select id="selectOrders" resultType="com.your.package.entity.Order">
SELECT * FROM orders WHERE entity_id = #{id}
</select>
高级篇
1. 缓存
MyBatis支持一级缓存和二级缓存。
1.1 一级缓存
一级缓存默认开启,作用域为SqlSession,适用于查询操作。
1.2 二级缓存
二级缓存作用域为全局,适用于频繁查询且数据变化不频繁的场景。
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
2. 插件
MyBatis插件可以拦截SQL执行过程,实现分页、日志记录等功能。
@Intercepts({
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class PaginationInterceptor implements Interceptor {
// 实现分页逻辑
}
实战篇
1. 实现分页查询
public interface YourMapper {
List<YourEntity> selectByPage(int offset, int limit);
}
<select id="selectByPage" resultMap="YourEntityResultMap">
SELECT * FROM your_table LIMIT #{limit} OFFSET #{offset}
</select>
2. 实现日志记录
public class LoggingInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
try {
// 打印SQL语句
MappedStatement mappedStatement = (MappedStatement) invocation.getTarget();
String sql = mappedStatement.getBoundSql().getSql();
System.out.println("SQL: " + sql);
// 执行SQL
return invocation.proceed();
} finally {
// 打印执行时间
long startTime = System.currentTimeMillis();
Object result = invocation.proceed();
long endTime = System.currentTimeMillis();
System.out.println("Execution time: " + (endTime - startTime) + "ms");
}
}
}
总结
通过本文的学习,相信你已经对MyBatis有了更深入的了解。MyBatis是一个非常强大的框架,能够帮助我们轻松搞定数据库操作。在实际开发中,我们可以根据需求选择合适的配置和技巧,提高开发效率。
