MyBatis 是一款优秀的持久层框架,它消除了几乎所有的 JDBC 代码和手动设置参数以及获取结果集的过程。MyBatis 可以使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 POJOs(Plain Old Java Objects,简单的 Java 对象)映射成数据库中的记录。
入门教程
1. 环境搭建
首先,确保你的开发环境中已经安装了Java和Maven。然后,你可以创建一个新的Maven项目,并在pom.xml中添加MyBatis的依赖:
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.7</version>
</dependency>
<!-- 添加数据库连接池依赖,例如:HikariCP -->
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>4.0.3</version>
</dependency>
<!-- 添加数据库驱动依赖,例如:MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.26</version>
</dependency>
</dependencies>
2. 创建配置文件
在src/main/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/mydb"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
</environment>
</environments>
</configuration>
3. 创建映射文件
在src/main/resources/mapper目录下创建相应的映射文件,例如UserMapper.xml:
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectById" resultType="com.example.entity.User">
SELECT * FROM user WHERE id = #{id}
</select>
</mapper>
4. 编写接口
在src/main/java/com/example/mapper目录下创建对应的接口,例如UserMapper.java:
package com.example.mapper;
import com.example.entity.User;
import org.apache.ibatis.annotations.Select;
public interface UserMapper {
User selectById(Long id);
}
5. 编写服务层
在src/main/java/com/example/service目录下创建服务层代码,例如UserService.java:
package com.example.service;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserById(Long id) {
return userMapper.selectById(id);
}
}
应用案例
下面是一个简单的应用案例,展示如何使用MyBatis查询用户信息。
1. 创建数据库
首先,创建一个名为mydb的数据库,并创建一个名为user的表,包含字段id(主键)、name和age。
CREATE DATABASE mydb;
USE mydb;
CREATE TABLE user (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
age INT
);
2. 添加数据
向user表中添加一些测试数据:
INSERT INTO user (name, age) VALUES ('Alice', 30);
INSERT INTO user (name, age) VALUES ('Bob', 25);
3. 使用MyBatis查询数据
现在,使用MyBatis查询用户名为Alice的用户信息。
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUserByName(String name) {
return userMapper.selectByName(name);
}
}
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectByName" resultType="com.example.entity.User">
SELECT * FROM user WHERE name = #{name}
</select>
</mapper>
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService userService = context.getBean(UserService.class);
User user = userService.getUserByName("Alice");
System.out.println(user.getName() + ", " + user.getAge());
}
输出结果:
Alice, 30
实战技巧详解
1. 映射文件命名规范
在创建映射文件时,建议遵循以下命名规范:
- 接口名和映射文件名一致,并且接口名使用驼峰命名法。
- 映射文件名以
Mapper结尾。
例如,UserMapper.java对应的映射文件应为UserMapper.xml。
2. 动态SQL
MyBatis支持动态SQL,你可以使用<if>、<choose>、<when>、<otherwise>等标签来实现条件判断。
<select id="selectByCondition" resultType="com.example.entity.User">
SELECT * FROM user
<where>
<if test="name != null and name != ''">
AND name = #{name}
</if>
<if test="age != null">
AND age = #{age}
</if>
</where>
</select>
3. 缓存
MyBatis提供了二级缓存机制,可以减少数据库查询次数,提高应用性能。
- 开启二级缓存:在
mybatis-config.xml配置文件中添加<settings>标签,并设置cacheEnabled属性为true。
<settings>
<setting name="cacheEnabled" value="true"/>
</settings>
- 配置二级缓存:在映射文件中添加
<cache>标签。
<mapper namespace="com.example.mapper.UserMapper">
<cache/>
</mapper>
4. 插入、更新和删除操作
MyBatis也支持插入、更新和删除操作。使用<insert>、<update>和<delete>标签,并使用#{}来绑定参数。
<insert id="insertUser" parameterType="com.example.entity.User">
INSERT INTO user (name, age) VALUES (#{name}, #{age})
</insert>
<update id="updateUser" parameterType="com.example.entity.User">
UPDATE user SET name = #{name}, age = #{age} WHERE id = #{id}
</update>
<delete id="deleteUser" parameterType="long">
DELETE FROM user WHERE id = #{id}
</delete>
5. 分布式数据库访问
MyBatis支持分布式数据库访问,可以通过配置数据源来实现。
- 配置数据源:在
mybatis-config.xml配置文件中添加多个<dataSource>标签。
<dataSource type="JDBC">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/db1"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
<dataSource type="JDBC">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/db2"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</dataSource>
- 在映射文件中,使用不同的
namespace和id来区分不同数据源的操作。
<mapper namespace="com.example.mapper.UserMapper1">
<select id="selectById" resultType="com.example.entity.User">
SELECT * FROM db1.user WHERE id = #{id}
</select>
</mapper>
<mapper namespace="com.example.mapper.UserMapper2">
<select id="selectById" resultType="com.example.entity.User">
SELECT * FROM db2.user WHERE id = #{id}
</select>
</mapper>
以上是Java开源框架MyBatis的入门教程、应用案例与实战技巧详解。希望这些内容能够帮助你更好地理解和掌握MyBatis。
