怎么实现 MyBatis-Plus 的 Mapper 对象创建和获取
时间: 2024-03-13 12:42:59 浏览: 33
创建和获取 MyBatis-Plus 的 Mapper 对象,可以通过以下两种方式进行:
1. 使用 Spring Boot 自动装配
如果您的项目使用了 Spring Boot,可以直接使用 Spring Boot 提供的自动装配机制来创建和获取 MyBatis-Plus 的 Mapper 对象。具体来说,您需要完成以下两个步骤:
1. 在 `application.properties` 或 `application.yml` 中配置 MyBatis-Plus 的相关参数,包括数据源配置、Mapper 扫描路径等。例如:
```yaml
# 数据源配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=123456
# MyBatis-Plus 配置
mybatis-plus.mapper-locations=classpath:mapper/**/*.xml
mybatis-plus.type-aliases-package=com.example.entity
```
2. 在需要使用 Mapper 对象的地方,通过 `@Autowired` 注解注入对应的 Mapper 对象即可。例如:
```java
@RestController
public class MyController {
@Autowired
private MyMapper myMapper;
@GetMapping("/getVariable")
public String getVariable() {
return myMapper.getVariable();
}
}
```
在上述代码中,我们使用 `@Autowired` 注解将 `MyMapper` 对象注入到了 `MyController` 控制器中,并在 `getVariable` 方法中使用该对象查询数据库并返回结果。
2. 手动创建 Mapper 对象
如果您的项目没有使用 Spring Boot,或者需要手动创建 Mapper 对象,可以通过以下步骤进行:
1. 在 `pom.xml` 中引入 MyBatis-Plus 的依赖:
```xml
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
```
2. 在需要使用 Mapper 对象的地方,通过 `SqlSessionFactory` 和 `MapperRegistry` 对象手动创建 Mapper 对象。例如:
```java
public class MyBatisPlusUtils {
// 获取 SqlSessionFactory 对象
private static SqlSessionFactory getSqlSessionFactory() {
// 创建数据源对象
DataSource dataSource = new PooledDataSource(
"com.mysql.jdbc.Driver",
"jdbc:mysql://localhost:3306/mydatabase",
"root",
"123456"
);
// 创建 MyBatis 配置对象
MybatisConfiguration configuration = new MybatisConfiguration();
configuration.setMapUnderscoreToCamelCase(true);
// 创建 SqlSessionFactory 对象
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder()
.build(configuration, dataSource);
return sessionFactory;
}
// 获取 Mapper 对象
public static <T> T getMapper(Class<T> mapperClass) {
// 创建 SqlSessionFactory 对象
SqlSessionFactory sessionFactory = getSqlSessionFactory();
// 创建 MapperRegistry 对象
MapperRegistry mapperRegistry = new MapperRegistry(sessionFactory.getConfiguration());
// 注册 Mapper 对象
mapperRegistry.addMapper(mapperClass);
// 获取 Mapper 对象
return sessionFactory.openSession().getMapper(mapperClass);
}
}
```
在上述代码中,我们定义了一个 `getSqlSessionFactory` 方法,用于创建 `SqlSessionFactory` 对象;并定义了一个 `getMapper` 方法,用于手动创建 Mapper 对象。在 `getMapper` 方法中,我们首先通过 `getSqlSessionFactory` 方法获取到了 `SqlSessionFactory` 对象,然后创建了一个 `MapperRegistry` 对象,并将需要创建的 Mapper 对象注册到了该对象中;最后通过 `SqlSessionFactory` 对象的 `openSession` 方法获取到了一个 `SqlSession` 对象,并调用该对象的 `getMapper` 方法获取到了需要的 Mapper 对象。