springboot整合mybatisplus+pgsql
时间: 2025-04-19 10:43:50 浏览: 35
### Spring Boot 整合 MyBatis Plus 和 PostgreSQL 示例教程
#### 1. 添加依赖项
为了使 Spring Boot 应用程序能够与 MyBatis Plus 及 PostgreSQL 数据库协同工作,需在 `pom.xml` 文件中引入必要的依赖。
```xml
<dependencies>
<!-- Spring Boot Starter Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis Plus -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<!-- PostgreSQL JDBC Driver -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Lombok (可选,简化Java代码编写) -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- 测试支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
```
#### 2. 配置数据源和MyBatis Plus
编辑 `application.properties` 或者 `application.yml` 来指定连接到PostgreSQL的数据源属性以及一些基本的MyBatis Plus配置选项。
对于 `application.properties`:
```properties
# DataSource Configurations
spring.datasource.url=jdbc:postgresql://localhost:5432/your_database_name
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=org.postgresql.Driver
# MyBatis Plus Configuration
mybatis-plus.configuration.map-underscore-to-camel-case=true
mybatis-plus.global-config.db-config.id-type=auto
```
对于 `application.yml`:
```yaml
spring:
datasource:
url: jdbc:postgresql://localhost:5432/your_database_name
username: your_username
password: your_password
driver-class-name: org.postgresql.Driver
mybatis-plus:
configuration:
map-underscore-to-camel-case: true
global-config:
db-config:
id-type: auto
```
#### 3. 创建实体类、Mapper接口和服务层逻辑
创建相应的实体类来映射数据库表结构;定义 Mapper 接口继承自 BaseMapper 并实现特定业务方法;最后,在服务层调用这些方法完成CRUD操作。
例如:
##### 实体类 User.java
```java
@Data
@TableName("users")
public class User {
private Long id;
private String name;
private Integer age;
}
```
##### Mapper接口 IUserMapper.java
```java
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
public interface IUserMapper extends BaseMapper<User> {}
```
##### Service 类 UserServiceImpl.java
```java
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private IUserMapper userMapper;
@Override
public List<User> getAllUsers() {
return userMapper.selectList(null);
}
}
```
#### 4. 启动器配置
确保应用程序启动时自动扫描并注册所有的Mapper接口。这可以通过创建一个带有适当注解的配置类来实现。
```java
@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = {"com.example.mapper"})
public class MybatisPlusConfig {
}
```
通过上述步骤可以成功地将Spring Boot应用与MyBatis Plus框架相结合,并使其能顺利访问PostgreSQL数据库[^1][^2]。
阅读全文
相关推荐


















