在Java领域,MyBatis是一个非常流行的持久层框架,它能够帮助开发者以简单的方式实现数据库的访问和操作。本文将为你提供一份MyBatis实战指南,从入门到进阶,助你轻松掌握这一强大的工具。
入门篇
1. MyBatis简介
MyBatis是一个优秀的持久层框架,它对JDBC进行了封装,简化了数据库操作。MyBatis可以让你以XML或注解的方式配置SQL映射,将接口和XML或注解中的SQL语句关联起来,实现数据库的CRUD操作。
2. 环境搭建
2.1 创建Maven项目
- 打开Maven的官方网站,下载Maven安装包。
- 解压安装包,配置环境变量。
- 打开命令行,执行
mvn -version验证Maven是否安装成功。
2.2 添加依赖
在项目的pom.xml文件中添加以下依赖:
<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>
3. 配置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/test"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml"/>
</mappers>
</configuration>
4. 编写Mapper接口和XML
在com.example.mapper包下创建一个名为UserMapper.java的接口,定义数据库操作方法:
package com.example.mapper;
public interface UserMapper {
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}
在src/main/resources目录下创建一个名为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">
<resultMap id="BaseResultMap" type="com.example.entity.User">
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="username" property="username" jdbcType="VARCHAR"/>
<result column="password" property="password" jdbcType="VARCHAR"/>
</resultMap>
<sql id="Base_Column_List">
id, username, password
</sql>
<insert id="insert" parameterType="com.example.entity.User">
insert into user (id, username, password)
values (#{id}, #{username}, #{password})
</insert>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List"/>
from user
where id = #{id}
</select>
<update id="updateByPrimaryKeySelective" parameterType="com.example.entity.User">
update user
<set>
<if test="username != null">
username = #{username},
</if>
<if test="password != null">
password = #{password},
</if>
</set>
where id = #{id}
</update>
<update id="updateByPrimaryKey" parameterType="com.example.entity.User">
update user
set username = #{username},
password = #{password}
where id = #{id}
</update>
</mapper>
5. 使用MyBatis
在项目中创建一个名为MyBatisDemo.java的类,用于测试MyBatis:
package com.example.demo;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisDemo {
public static void main(String[] args) {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(MyBatisDemo.class.getClassLoader().getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
try {
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.selectByPrimaryKey(1);
System.out.println(user.getUsername());
sqlSession.commit();
} finally {
sqlSession.close();
}
}
}
进阶篇
1. 动态SQL
MyBatis支持动态SQL,可以方便地实现复杂的SQL语句。例如,使用<if>、<choose>、<foreach>等标签:
<select id="selectUsersByConditions" parameterType="map" resultType="User">
select
<include refid="Base_Column_List"/>
from user
<where>
<if test="username != null">
and username = #{username}
</if>
<if test="password != null">
and password = #{password}
</if>
<choose>
<when test="id != null">
and id = #{id}
</when>
<otherwise>
and id > 0
</otherwise>
</choose>
</where>
</select>
2. 插件
MyBatis提供了插件机制,可以自定义插件来扩展其功能。例如,创建一个Interceptor实现类,在执行SQL语句前进行一些操作:
package com.example.interceptor;
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 LogInterceptor 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-config.xml中注册插件:
<plugins>
<plugin interceptor="com.example.interceptor.LogInterceptor"/>
</plugins>
3. 缓存
MyBatis提供了两种缓存机制:一级缓存和二级缓存。
3.1 一级缓存
一级缓存是SqlSession级别的缓存,默认开启。在同一个SqlSession中,相同的查询会被缓存起来,避免重复查询。
3.2 二级缓存
二级缓存是Mapper级别的缓存,可以跨SqlSession共享。通过在Mapper接口中添加@Cache注解,可以配置二级缓存:
@Cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"
public interface UserMapper {
// ...
}
4. 多数据库支持
MyBatis支持多种数据库,可以通过在mybatis-config.xml中配置数据库类型来实现:
<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="oracle">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
在MyBatis的配置文件中,通过设置<databaseId>标签,可以针对不同的数据库类型执行不同的SQL语句:
<databaseIdProvider type="DB_VENDOR">
<property name="MySQL" value="mysql"/>
<property name="Oracle" value="oracle"/>
</databaseIdProvider>
在Mapper XML中,通过<choose>标签选择不同的SQL语句:
<select id="selectUsers" resultType="User">
<choose>
<when test="databaseId == 'mysql'">
select * from user
</when>
<when test="databaseId == 'oracle'">
select * from user_table
</when>
<otherwise>
select * from user
</otherwise>
</choose>
</select>
总结
本文从入门到进阶,详细介绍了MyBatis的使用方法和技巧。通过学习本文,相信你已经掌握了MyBatis的核心知识。在实际项目中,不断积累经验,不断优化代码,你将能够更好地利用MyBatis的优势。祝你学习愉快!
