MyBatis简介
MyBatis是一款优秀的持久层框架,它消除了几乎所有的JDBC代码和手动设置参数以及获取结果集的过程。MyBatis通过简单的XML或注解用于配置和原始映射,将接口和Java的POJOs(Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。
入门篇
1. MyBatis环境搭建
首先,你需要下载MyBatis的jar包。接着,创建一个Maven项目,在pom.xml文件中添加以下依赖:
<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.22</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/test"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml"/>
</mappers>
</configuration>
3. Mapper接口和XML映射文件
创建UserMapper.java接口:
public interface UserMapper {
User getUserById(Integer id);
}
创建对应的XML映射文件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="getUserById" resultType="com.example.entity.User">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
进阶篇
1. 动态SQL
MyBatis支持动态SQL,你可以使用<if>、<choose>、<foreach>等标签来编写动态SQL。
<select id="getUserByCondition" resultType="com.example.entity.User">
SELECT * FROM user
<where>
<if test="id != null">
AND id = #{id}
</if>
<if test="username != null">
AND username = #{username}
</if>
</where>
</select>
2. 缓存
MyBatis提供了两种类型的缓存:一级缓存和二级缓存。
- 一级缓存:基于SqlSession的缓存,默认开启。
- 二级缓存:基于namespace的缓存,需要手动开启。
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
3. 插件
MyBatis插件可以拦截数据库执行的整个过程,例如执行器、参数处理器、结果处理器等。
@Intercepts({
@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})
})
public class ExamplePlugin implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
// 在这里进行拦截
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
// 设置插件属性
}
}
精通篇
1. 代码生成器
MyBatis提供了代码生成器MyBatis Generator,可以自动生成实体类、Mapper接口和XML映射文件。
public class MyBatisGenerator {
public static void main(String[] args) throws Exception {
Configuration config = new Configuration();
// 设置数据库连接信息
// 设置生成文件的路径
// 设置生成的实体类、Mapper接口和XML映射文件
new MyBatisGenerator().generate(config);
}
}
2. 自定义TypeHandler
TypeHandler用于将Java类型和数据库类型之间进行转换。
@MappedTypes({Integer.class, Long.class})
public class IntegerTypeHandler extends BaseTypeHandler<Integer> {
@Override
public void setParameter(PreparedStatement ps, int i, Integer parameter, JdbcType jdbcType) throws SQLException {
ps.setInt(i, parameter);
}
@Override
public Integer getResult(ResultSet rs, String columnName) throws SQLException {
return rs.getInt(columnName);
}
@Override
public Integer getResult(ResultSet rs, int columnIndex) throws SQLException {
return rs.getInt(columnIndex);
}
@Override
public Integer getResult(CallableStatement cs, int columnIndex) throws SQLException {
return cs.getInt(columnIndex);
}
}
3. 多数据源
MyBatis支持多数据源,你可以通过配置文件或注解来实现。
<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/test"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</environment>
<environment id="mysql">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mysql"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
总结
MyBatis是一款功能强大的持久层框架,它可以帮助你快速、高效地完成数据库操作。通过本文的介绍,相信你已经对MyBatis有了初步的了解。在实际开发过程中,你可以根据自己的需求选择合适的配置和使用技巧,从而提高开发效率。
