MyBatis是一款优秀的持久层框架,它支持定制化SQL、存储过程以及高级映射。MyBatis避免了几乎所有的JDBC代码和手动设置参数以及获取结果集的工作。本文将详细介绍MyBatis的基本概念、实践应用以及一些经典案例解析。
MyBatis基础概念
1. ORM概念
ORM(Object-Relational Mapping,对象关系映射)是一种技术,它允许在对象模型和关系数据库之间建立映射关系。通过ORM框架,可以将数据库中的数据映射为Java对象,简化了数据持久化操作。
2. MyBatis核心组件
- SqlSession:MyBatis的核心接口,用于执行各种数据库操作,如查询、更新、删除等。
- Executor:负责执行SQL语句并返回结果。
- Mapper:MyBatis中的映射接口,定义了SQL语句与Java对象的映射关系。
- Configuration:MyBatis的全局配置文件,用于配置数据库连接、事务管理等信息。
MyBatis实践应用
1. 环境搭建
首先,我们需要在项目中添加MyBatis依赖。以下是Maven依赖示例:
<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. 配置文件
在resources目录下创建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="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/mapper/UserMapper.xml"/>
</mappers>
</configuration>
3. Mapper接口
在com/example/mapper包下创建UserMapper.java接口,定义SQL语句与Java对象的映射关系。
public interface UserMapper {
User selectById(int id);
int insert(User user);
int update(User user);
int delete(int id);
}
4. Mapper XML
在com/example/mapper包下创建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 user WHERE id = #{id}
</select>
<insert id="insert">
INSERT INTO user (name, age) VALUES (#{name}, #{age})
</insert>
<update id="update">
UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}
</update>
<delete id="delete">
DELETE FROM user WHERE id = #{id}
</delete>
</mapper>
5. 测试
在主程序中,通过SqlSession执行Mapper接口中的方法。
public static void main(String[] args) throws IOException {
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(new FileInputStream("src/main/resources/mybatis-config.xml"));
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.selectById(1);
System.out.println(user);
}
}
案例解析
1. 分页查询
MyBatis支持分页查询,以下是一个分页查询的示例:
<select id="selectPage" resultType="com.example.entity.User">
SELECT * FROM user LIMIT #{offset}, #{pageSize}
</select>
在Java代码中,我们可以使用PageHelper插件实现分页功能。
PageHelper.startPage(1, 10);
List<User> users = mapper.selectPage();
2. 动态SQL
MyBatis支持动态SQL,以下是一个动态SQL的示例:
<select id="selectByCondition" 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>
在Java代码中,我们可以使用Ognl表达式来构建动态SQL。
Map<String, Object> params = new HashMap<>();
params.put("name", "张三");
params.put("age", 20);
List<User> users = mapper.selectByCondition(params);
总结
MyBatis是一款功能强大的持久层框架,通过MyBatis,我们可以简化数据库操作,提高开发效率。本文详细介绍了MyBatis的基本概念、实践应用以及一些经典案例解析,希望对您有所帮助。
