MyBatis 是一个优秀的持久层框架,它消除了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的过程。MyBatis 可以使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
MyBatis 快速上手
1. 添加依赖
首先,你需要在你的项目中添加 MyBatis 的依赖。如果你使用 Maven,可以在 pom.xml 文件中添加以下依赖:
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-redis</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
2. 配置数据源
在 application.properties 或 application.yml 文件中配置数据源:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
3. 创建 MyBatis 配置文件
创建一个 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/mydb"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
</configuration>
4. 创建映射文件
创建一个映射文件 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">
<select id="selectById" resultType="com.example.entity.User">
SELECT * FROM users WHERE id = #{id}
</select>
</mapper>
5. 创建接口
创建一个 UserMapper 接口,定义方法:
package com.example.mapper;
import com.example.entity.User;
public interface UserMapper {
User selectById(Integer id);
}
6. 创建实体类
创建一个 User 实体类:
package com.example.entity;
public class User {
private Integer id;
private String name;
private String email;
// getters and setters
}
7. 测试
在主类中注入 UserMapper,并调用方法测试:
package com.example;
import com.example.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(Application.class, args);
UserMapper userMapper = context.getBean(UserMapper.class);
User user = userMapper.selectById(1);
System.out.println(user);
}
}
MyBatis 实战技巧
1. 使用注解
MyBatis 提供了注解方式来定义映射关系,这样可以减少 XML 配置文件的使用。
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{id}")
User selectById(Integer id);
}
2. 动态 SQL
MyBatis 提供了动态 SQL 功能,可以根据条件动态拼接 SQL 语句。
@Select({
"<script>",
"SELECT * FROM users",
"<where>",
"<if test='name != null'>",
"name = #{name}",
"</if>",
"</where>",
"</script>"
})
List<User> selectByName(String name);
3. 缓存
MyBatis 提供了两种类型的缓存:一级缓存和二级缓存。一级缓存是针对同一个 Mapper 的请求,二级缓存是针对整个应用。
@CacheNamespace eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
MyBatis 最佳实践指南
1. 遵循三层架构
将业务逻辑、数据访问和表示层分开,遵循三层架构。
2. 使用注解或 XML 配置
根据项目需求选择使用注解或 XML 配置。
3. 避免硬编码
避免在代码中硬编码数据库连接信息,使用配置文件或注解。
4. 使用日志
使用日志记录 SQL 语句和执行结果,方便调试和问题追踪。
5. 性能优化
使用分页查询、索引等手段优化性能。
通过以上内容,相信你已经对 MyBatis 有了一定的了解。在实际开发过程中,不断积累经验,总结技巧,才能更好地利用 MyBatis 框架。
