MyBatis 是一个优秀的持久层框架,它消除了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的过程。MyBatis 可以使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs(Plain Old Java Objects,简单的Java对象)映射成数据库中的记录。
MyBatis 简介
MyBatis 的核心思想是将 SQL 映射成 Java 方法,这样开发者就可以在 Java 代码中直接调用 SQL 语句,而不需要在 Java 代码中编写繁琐的 JDBC 代码。这使得 Java 开发者可以更加专注于业务逻辑的实现,提高开发效率。
MyBatis 的优势
- 易学易用:MyBatis 的学习曲线相对平缓,即使是刚接触 Java 开发的开发者也能快速上手。
- 高性能:MyBatis 通过预编译 SQL 提高了数据库访问性能。
- 灵活的映射:MyBatis 支持多种映射方式,包括 XML 映射、注解映射和内联映射等。
- 支持多种数据库:MyBatis 支持多种数据库,如 MySQL、Oracle、SQL Server 等。
MyBatis 入门
环境搭建
- 下载 MyBatis:从 MyBatis 官网下载最新版本的 MyBatis 包。
- 添加依赖:在项目的
pom.xml文件中添加 MyBatis 的依赖。
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
- 配置 MyBatis:在项目的
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.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
</configuration>
- 编写 SQL 映射文件:在
resources目录下创建 SQL 映射文件,例如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="selectUserById" resultType="com.example.entity.User">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
- 编写接口:在
com.example.mapper包下创建UserMapper接口。
package com.example.mapper;
public interface UserMapper {
User selectUserById(int id);
}
- 使用 MyBatis:在 Java 代码中,使用
SqlSessionFactoryBuilder创建SqlSessionFactory,然后通过SqlSessionFactory获取SqlSession,最后通过SqlSession执行 SQL 映射文件中的 SQL 语句。
package com.example;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisExample {
public static void main(String[] args) {
try {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build();
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.selectUserById(1);
System.out.println(user.getName());
sqlSession.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
MyBatis 进阶
动态 SQL
MyBatis 支持动态 SQL,可以在 SQL 映射文件中使用 <if>、<choose>、<when>、<otherwise> 等标签实现动态 SQL。
<select id="selectUserByCondition" resultType="com.example.entity.User">
SELECT * FROM user
<where>
<if test="name != null">
AND name = #{name}
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
类型处理器
MyBatis 提供了类型处理器,可以将 Java 类型映射到数据库类型。例如,可以将 Java 中的 Date 类型映射到数据库中的 TIMESTAMP 类型。
public class DateTypeHandler extends BaseTypeHandler<Date> {
@Override
public void setParameter(PreparedStatement ps, int i, Date parameter, JdbcType jdbcType) throws SQLException {
if (parameter == null) {
ps.setNull(i, Types.TIMESTAMP);
} else {
ps.setDate(i, new java.sql.Date(parameter.getTime()));
}
}
@Override
public Date getResult(ResultSet rs, String columnName) throws SQLException {
java.sql.Date sqlDate = rs.getDate(columnName);
return sqlDate == null ? null : new Date(sqlDate.getTime());
}
@Override
public Date getResult(ResultSet rs, int columnIndex) throws SQLException {
java.sql.Date sqlDate = rs.getDate(columnIndex);
return sqlDate == null ? null : new Date(sqlDate.getTime());
}
@Override
public Date getResult(CallableStatement cs, int columnIndex) throws SQLException {
java.sql.Date sqlDate = cs.getDate(columnIndex);
return sqlDate == null ? null : new Date(sqlDate.getTime());
}
}
扩展 MyBatis
MyBatis 允许开发者扩展 MyBatis 的功能,例如自定义 ResultHandler、TypeHandler 等。
public class CustomTypeHandler extends BaseTypeHandler<String> {
@Override
public void setParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
ps.setString(i, parameter);
}
@Override
public String getResult(ResultSet rs, String columnName) throws SQLException {
return rs.getString(columnName);
}
@Override
public String getResult(ResultSet rs, int columnIndex) throws SQLException {
return rs.getString(columnIndex);
}
@Override
public String getResult(CallableStatement cs, int columnIndex) throws SQLException {
return cs.getString(columnIndex);
}
}
总结
MyBatis 是一个功能强大、易学易用的持久层框架。通过本文的介绍,相信你已经对 MyBatis 有了一定的了解。希望本文能帮助你轻松入门 MyBatis,并在实际项目中应用 MyBatis 的核心功能,提高你的开发效率。
