MyBatis 是一个优秀的持久层框架,它消除了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的工作。MyBatis 可以使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs(Plain Old Java Objects,简单的 Java 对象)映射成数据库中的记录。
MyBatis 的核心概念
1. Mapper 接口和 XML 映射文件
MyBatis 的核心是 Mapper 接口和 XML 映射文件。Mapper 接口定义了数据库操作的方法,而 XML 映射文件则包含了 SQL 语句和相关的映射规则。
public interface UserMapper {
User getUserById(Integer id);
}
对应的 XML 映射文件:
<mapper namespace="com.example.mapper.UserMapper">
<select id="getUserById" resultType="com.example.User">
SELECT * FROM users WHERE id = #{id}
</select>
</mapper>
2. SQL 映射语句
MyBatis 允许你使用预定义的 SQL 语句来操作数据库。这些 SQL 语句可以定义在 XML 映射文件中,也可以通过注解直接在接口方法上。
@Select("SELECT * FROM users WHERE id = #{id}")
User getUserById(@Param("id") Integer id);
3. 结果映射
MyBatis 使用结果映射来将 SQL 结果集中的列映射到 Java 对象的属性上。
<resultMap id="userMap" type="User">
<result property="id" column="id"/>
<result property="username" column="username"/>
<result property="email" column="email"/>
</resultMap>
4. 缓存
MyBatis 提供了强大的缓存机制,可以缓存 SQL 查询的结果,从而提高性能。
<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/>
MyBatis 的强大功能
1. 灵活的数据绑定
MyBatis 支持灵活的数据绑定,允许你将任何类型的参数传递给 SQL 映射语句。
@Select("SELECT * FROM users WHERE username = #{username, jdbcType=VARCHAR}")
List<User> findUsersByUsername(@Param("username") String username);
2. 动态 SQL
MyBatis 允许你编写动态 SQL,可以根据不同的条件执行不同的 SQL 语句。
<select id="findUsersByCondition" resultType="User">
SELECT * FROM users
<where>
<if test="username != null">
AND username = #{username}
</if>
<if test="email != null">
AND email = #{email}
</if>
</where>
</select>
3. 支持自定义类型处理器
MyBatis 支持自定义类型处理器,可以将数据库中的类型转换为 Java 类型。
public class LocalDateTypeHandler extends BaseTypeHandler<LocalDate> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, LocalDate parameter, JdbcType jdbcType) throws SQLException {
ps.setDate(i, new Date(parameter.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()));
}
@Override
public LocalDate getNullableResult(ResultSet rs, String columnName) throws SQLException {
Timestamp timestamp = rs.getTimestamp(columnName);
if (timestamp != null) {
return timestamp.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}
return null;
}
@Override
public LocalDate getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
Timestamp timestamp = rs.getTimestamp(columnIndex);
if (timestamp != null) {
return timestamp.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}
return null;
}
@Override
public LocalDate getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
Timestamp timestamp = cs.getTimestamp(columnIndex);
if (timestamp != null) {
return timestamp.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}
return null;
}
}
应用实战
1. 创建 MyBatis 项目
首先,你需要创建一个 MyBatis 项目。你可以使用任何 IDE 来创建项目,例如 Eclipse 或 IntelliJ IDEA。
2. 配置 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.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mydb"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml"/>
</mappers>
</configuration>
3. 编写 Mapper 接口和 XML 映射文件
在项目中创建对应的 Mapper 接口和 XML 映射文件。
4. 使用 MyBatis
在你的 Java 代码中,使用 MyBatis 的 SqlSessionFactory 和 SqlSession 来执行数据库操作。
public class Application {
public static void main(String[] args) throws IOException {
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession session = sqlSessionFactory.openSession()) {
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user.getUsername());
}
}
}
通过以上步骤,你就可以开始使用 MyBatis 来操作数据库了。MyBatis 的强大功能和灵活配置,使其成为 Java 开发中一个非常有用的工具。
