在Java开发中,数据库交互是必不可少的环节。MyBatis作为一款优秀的持久层框架,可以帮助开发者轻松实现数据库的增删改查等操作。本文将带你从入门到进阶,掌握MyBatis的使用技巧。
入门篇
1. MyBatis简介
MyBatis是一款优秀的持久层框架,它对JDBC的操作进行了封装,简化了数据库交互的过程。MyBatis使用XML或注解来配置SQL映射,使得开发者可以更专注于业务逻辑的实现。
2. 环境搭建
2.1 添加依赖
在项目中添加MyBatis的依赖,可以使用以下Maven配置:
<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.26</version>
</dependency>
</dependencies>
2.2 配置数据源
在application.properties或application.yml文件中配置数据源信息,如数据库连接URL、用户名、密码等。
# application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
2.3 创建MyBatis配置文件
在项目的src/main/resources目录下创建mybatis-config.xml文件,配置MyBatis的相关信息,如数据源、事务管理器、映射器等。
<?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?useUnicode=true&characterEncoding=UTF-8&useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml"/>
</mappers>
</configuration>
3. 编写Mapper接口和XML
3.1 Mapper接口
创建一个Mapper接口,定义数据库操作的SQL语句。
package com.example.mapper;
import com.example.entity.User;
public interface UserMapper {
User selectById(Integer id);
int insert(User user);
int update(User user);
int delete(Integer id);
}
3.2 XML配置
在src/main/resources目录下创建对应的Mapper 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>
<insert id="insert">
INSERT INTO user (name, age) VALUES (#{name}, #{age})
</insert>
<update id="update">
UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}
</update>
<delete id="delete">
DELETE FROM user WHERE id = #{id}
</delete>
</mapper>
4. 使用MyBatis
在Spring项目中,可以通过以下方式使用MyBatis:
package com.example.service;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(Integer id) {
return userMapper.selectById(id);
}
public int insertUser(User user) {
return userMapper.insert(user);
}
public int updateUser(User user) {
return userMapper.update(user);
}
public int deleteUser(Integer id) {
return userMapper.delete(id);
}
}
进阶篇
1. 动态SQL
MyBatis支持动态SQL,可以根据不同的条件执行不同的SQL语句。
<if test="name != null">
AND name = #{name}
</if>
2. 缓存
MyBatis提供了两种类型的缓存:一级缓存和二级缓存。
- 一级缓存:默认开启,只针对同一个Mapper的同一个方法的有效期内有效。
- 二级缓存:在多个Mapper之间共享,需要手动开启。
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
3. 分页
MyBatis支持分页查询,可以通过插件或手动实现。
3.1 插件实现
package com.example.plugin;
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 PaginationInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
// 获取原始的SQL语句
String originalSql = statementHandler.getBoundSql().getSql();
// 添加分页参数
String sql = addPagination(originalSql);
// 替换原始的SQL语句
statementHandler.getBoundSql().setSql(sql);
return invocation.proceed();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
}
private String addPagination(String originalSql) {
// 根据实际情况添加分页参数
// ...
return originalSql;
}
}
3.2 手动实现
<select id="selectUsers" resultType="User">
SELECT * FROM user LIMIT #{offset}, #{limit}
</select>
4. 多表关联
MyBatis支持多种多表关联方式,如一对一、一对多、多对多。
<resultMap id="userMap" type="User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<association property="address" javaType="Address">
<id property="id" column="address_id"/>
<result property="street" column="street"/>
<result property="city" column="city"/>
</association>
</resultMap>
<select id="selectUser" resultMap="userMap">
SELECT u.id, u.name, u.age, a.id AS address_id, a.street, a.city
FROM user u
LEFT JOIN address a ON u.address_id = a.id
WHERE u.id = #{id}
</select>
总结
通过本文的学习,相信你已经掌握了MyBatis的基本用法和进阶技巧。在实际项目中,MyBatis可以帮助你轻松实现数据库交互,提高开发效率。希望本文能对你有所帮助。
