MyBatis简介
MyBatis是一款优秀的持久层框架,它消除了几乎所有的JDBC代码和手动设置参数以及获取结果集的过程。MyBatis通过XML或注解的方式配置和原始映射,将接口和Java的POJOs(Plain Old Java Objects,简单的Java对象)映射成数据库中的记录。
MyBatis基础
1. 环境搭建
首先,我们需要搭建一个Java开发环境,包括JDK、IDE(如IntelliJ IDEA或Eclipse)和数据库(如MySQL)。然后,在项目中引入MyBatis依赖。
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.22</version>
</dependency>
</dependencies>
2. MyBatis配置
在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/mydb?useSSL=false"/>
<property name="username" value="root"/>
<property name="password" value="password"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml"/>
</mappers>
</configuration>
3. Mapper接口和XML映射
定义一个Mapper接口,其中包含数据库操作的方法。
public interface UserMapper {
User selectById(int id);
}
在对应的XML映射文件中,配置SQL语句。
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectById" resultType="com.example.User">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
4. 测试
使用MyBatis提供的SqlSession来执行数据库操作。
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(new FileInputStream("mybatis-config.xml"));
try (SqlSession session = sqlSessionFactory.openSession()) {
UserMapper mapper = session.getMapper(UserMapper.class);
User user = mapper.selectById(1);
System.out.println(user.getName());
}
MyBatis进阶
1. 动态SQL
MyBatis支持动态SQL,如<if>、<choose>、<when>、<otherwise>等标签,可以根据条件动态生成SQL语句。
<select id="selectUsers" resultType="User">
SELECT * FROM user
<where>
<if test="username != null">
AND username = #{username}
</if>
<if test="email != null">
AND email = #{email}
</if>
</where>
</select>
2. 类型处理器
MyBatis允许自定义类型处理器,将Java类型和数据库类型进行转换。
@MappedTypes({Date.class, Time.class, Timestamp.class})
public class DateTypeHandler implements TypeHandler<Date> {
@Override
public void setParameter(PreparedStatement ps, Date parameter, int index) throws SQLException {
ps.setDate(index, new Date(parameter.getTime()));
}
@Override
public Date getResult(ResultSet rs, String columnName) throws SQLException {
return rs.getDate(columnName);
}
@Override
public Date getResult(ResultSet rs, int columnIndex) throws SQLException {
return rs.getDate(columnIndex);
}
@Override
public Date getResult(CallableStatement cs, int columnIndex) throws SQLException {
return cs.getDate(columnIndex);
}
}
3. 插件
MyBatis支持自定义插件,如分页插件、日志插件等。
public class PaginationInterceptor implements Interceptor {
@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) {
// 配置参数
}
}
4. 高级特性
MyBatis还提供了高级特性,如缓存、注解开发、执行器等。
总结
MyBatis是一款功能强大的ORM框架,通过本文的介绍,相信你已经对MyBatis有了更深入的了解。在实际开发中,合理运用MyBatis可以提高开发效率,降低代码复杂度。希望本文能帮助你更好地掌握MyBatis,祝你学习愉快!
