MyBatis 是一个优秀的持久层框架,它消除了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的过程。MyBatis 可以使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。
快速上手
环境搭建
- 添加依赖:在项目的
pom.xml文件中添加 MyBatis 的依赖。
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
- 配置文件:创建
mybatis-config.xml配置文件,配置数据源、事务管理器等。
<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/mybatis_db"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml"/>
</mappers>
</configuration>
- 编写 Mapper 接口:定义一个接口,声明方法。
public interface UserMapper {
User selectById(int id);
}
- 编写 Mapper XML:在
UserMapper.xml文件中编写 SQL 语句。
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectById" resultType="com.example.User">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
- 运行测试:编写测试用例,测试 MyBatis 的功能。
public class MyBatisTest {
public static void main(String[] args) throws IOException {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(new FileInputStream("src/main/resources/mybatis-config.xml"));
try (SqlSession session = sqlSessionFactory.openSession()) {
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.selectById(1);
System.out.println(user);
}
}
}
高效开发
- 动态 SQL:MyBatis 提供了丰富的动态 SQL 功能,可以轻松实现复杂查询。
<select id="selectByCondition" resultType="com.example.User">
SELECT * FROM user
<where>
<if test="name != null">
AND name = #{name}
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
- 缓存:MyBatis 提供了两种类型的缓存:一级缓存和二级缓存。
- 一级缓存:默认开启,缓存作用域为同一个 SqlSession。
- 二级缓存:需要手动开启,缓存作用域为同一个 Mapper。
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
- 插件:MyBatis 提供了插件机制,可以自定义插件实现扩展功能。
public class MyPlugin implements Plugin {
@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) {
// 获取插件配置
}
}
实战技巧
- 合理使用注解和 XML:根据项目需求选择合适的配置方式。
- 优化 SQL 语句:避免使用复杂的 SQL 语句,尽量使用简单的 SQL 语句。
- 使用缓存:合理使用缓存可以提高性能。
- 监控和优化:使用工具监控 MyBatis 的性能,并对其进行优化。
通过以上内容,相信你已经对 MyBatis 有了一定的了解。在实际开发中,不断积累经验,逐步提高开发效率。
