1.核心组件
- SqlSessionFactory:是 MyBatis 的核心,它负责创建
SqlSession
。通常使用SqlSessionFactoryBuilder
来构建SqlSessionFactory
。示例代码如下:
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
- SqlSession:提供了执行 SQL 语句的方法,如
selectOne
、selectList
、insert
、update
、delete
等。可以通过SqlSession
来操作数据库。示例:
try (SqlSession sqlSession = sqlSessionFactory.openSession()) {
User user = sqlSession.selectOne("selectUserById", 1);
System.out.println(user);
}
- Mapper:Mapper 是一个接口,它定义了 SQL 操作的方法。MyBatis 可以通过动态代理为这个接口生成实现类,从而实现对数据库的操作。例如:
public interface UserMapper {
User selectUserById(int id);
}
@对应的 XML 映射文件(UserMapper.xml):
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectUserById" parameterType="int" resultType="com.example.domain.User">
SELECT * FROM users WHERE id = #{id}
</select>
</mapper>
1. 创建 Spring Boot 项目
首先,你可以使用 Spring Initializr(https://start.spring.io/)来创建一个新的 Spring Boot 项目。在创建项目时,确保选择了以下依赖(如果是IEDA旗舰版只需勾选即可):
- Spring Web
- Spring Data JPA(可选,如果你使用 JPA 相关功能)
- MySQL Driver(如果使用 MySQL 数据库)
2. 添加 MyBatis 依赖
在项目的 pom.xml
文件中添加 MyBatis 和相关数据库驱动的依赖。如果使用 MySQL 数据库,示例如下:
<dependencies>
<!-- Spring Boot Starter MyBatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.6</version>
</dependency>
<!-- MySQL Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
3. 配置数据源
在 application.properties
或 application.yml
文件中配置数据库连接信息。以 application.yml
为例:
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/your_database_name
username: your_username
password: your_password
4. 创建实体类
创建一个 Java 实体类来映射数据库表。例如,创建一个 User
实体类:
public class User {
private Long id;
private String username;
private String password;
// 省略 getters 和 setters 后面推荐用Lombok
}
5. 创建 Mapper 接口
创建一个 Mapper 接口,定义数据库操作方法。例如,创建一个 UserMapper
接口:
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{id}")
User findById(Long id);
}
这里使用了 @Mapper
注解标记该接口为 MyBatis 的 Mapper。如果不使用注解编写 SQL,也可以通过 XML 映射文件来实现。
6. 创建 XML 映射文件(可选)
如果不使用注解编写复杂 SQL,需要创建一个 XML 映射文件。在 resources
目录下创建 mapper
文件夹,并在其中创建 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-config.dtd">
<mapper namespace="com.example.mapper.UserMapper">
<select id="findById" parameterType="long" resultType="com.example.entity.User">
SELECT * FROM users WHERE id = #{id}
</select>
</mapper>
这里 namespace
要与 Mapper 接口的全限定名一致,id
要与接口中的方法名一致。
7. 配置 MyBatis
在 application.yml
文件中配置 MyBatis 的映射文件位置和实体类别名:
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.example.entity
8. 使用 Mapper
在服务层或控制器层中使用 Mapper 接口。例如,创建一个 UserService
并注入 UserMapper
:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User findUserById(Long id) {
return userMapper.findById(id);
}
}
9. 创建控制器
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/user/{id}")
public User getUserById(@PathVariable Long id) {
return userService.findUserById(id);
}
}
10. 启动项目
启动 Spring Boot 项目,访问 http://localhost:8080/user/{id}
,就可以获取到对应 id
的用户信息。