# SpringCloud中怎么利用MyBatis-Plus實現CRUD
## 一、前言
在現代微服務架構中,SpringCloud作為Java生態的主流框架,與MyBatis-Plus這一強大的ORM工具結合,能夠顯著提升開發效率。本文將詳細介紹如何在SpringCloud項目中整合MyBatis-Plus,并實現基礎的CRUD(Create, Read, Update, Delete)操作。
---
## 二、環境準備
### 1. 技術棧版本
- JDK 1.8+
- SpringBoot 2.7.x
- SpringCloud 2021.x
- MyBatis-Plus 3.5.x
- MySQL 8.0
### 2. 項目初始化
通過Spring Initializr創建項目,勾選以下依賴:
```xml
<dependencies>
<!-- SpringCloud Alibaba Nacos 服務發現 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- MyBatis-Plus 核心依賴 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3</version>
</dependency>
<!-- MySQL 驅動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
在application.yml
中配置數據源和MyBatis-Plus:
spring:
datasource:
url: jdbc:mysql://localhost:3306/mp_demo?useSSL=false
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 開啟SQL日志
global-config:
db-config:
logic-delete-field: deleted # 邏輯刪除字段
logic-delete-value: 1
logic-not-delete-value: 0
添加@MapperScan
注解掃描Mapper接口:
@SpringBootApplication
@MapperScan("com.example.mapper")
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
}
使用Lombok簡化代碼,通過注解實現字段映射:
@Data
@TableName("sys_user") // 指定表名
public class User {
@TableId(type = IdType.AUTO) // 主鍵自增
private Long id;
private String username;
private Integer age;
@TableField(fill = FieldFill.INSERT) // 自動填充
private LocalDateTime createTime;
@TableLogic // 邏輯刪除標記
private Integer deleted;
}
繼承MyBatis-Plus的BaseMapper
獲得基礎CRUD能力:
public interface UserMapper extends BaseMapper<User> {
// 自定義查詢方法
@Select("SELECT * FROM sys_user WHERE age > #{age}")
List<User> selectUsersOlderThan(Integer age);
}
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
public boolean addUser(User user) {
return userMapper.insert(user) > 0;
}
}
// 根據ID查詢
User user = userMapper.selectById(1L);
// 條件構造器查詢
LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(User::getUsername, "admin")
.between(User::getAge, 20, 30);
List<User> users = userMapper.selectList(wrapper);
需先配置分頁插件:
@Configuration
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
return interceptor;
}
}
使用示例:
Page<User> page = new Page<>(1, 10); // 當前頁,每頁數量
userMapper.selectPage(page, null);
// 根據ID更新
User user = new User();
user.setId(1L);
user.setAge(25);
userMapper.updateById(user);
// 條件更新
UpdateWrapper<User> wrapper = new UpdateWrapper<>();
wrapper.set("age", 30)
.eq("username", "admin");
userMapper.update(null, wrapper);
// 物理刪除
userMapper.deleteById(1L);
// 邏輯刪除(需配置邏輯刪除字段)
userMapper.deleteById(1L); // 實際執行的是UPDATE語句
實現MetaObjectHandler
接口:
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
}
}
@Version
private Integer version;
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
在微服務場景下可能需要連接多個數據庫:
@Configuration
@MapperScan(basePackages = "com.example.user.mapper", sqlSessionFactoryRef = "userSqlSessionFactory")
public class UserDataSourceConfig {
@Bean
@ConfigurationProperties("spring.datasource.user")
public DataSource userDataSource() {
return DataSourceBuilder.create().build();
}
@Bean
public SqlSessionFactory userSqlSessionFactory(@Qualifier("userDataSource") DataSource dataSource) throws Exception {
MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:mapper/user/*.xml"));
return factoryBean.getObject();
}
}
在服務間調用時處理MyBatis-Plus的Page對象序列化問題:
@FeignClient(name = "user-service")
public interface UserClient {
@PostMapping("/user/page")
CommonResult<Page<User>> getUserPage(@RequestBody PageQuery query);
}
saveBatch()
方法提升插入效率mybatis-plus.configuration.log-impl
通過本文的實踐,我們實現了: - SpringCloud與MyBatis-Plus的無縫整合 - 基礎CRUD操作的標準化實現 - 分頁查詢、邏輯刪除等企業級功能 - 微服務環境下的特殊配置處理
MyBatis-Plus的強大功能可以讓我們在SpringCloud微服務體系中減少約70%的SQL編寫工作量,同時保持代碼的可維護性和擴展性。
最佳實踐提示:建議將通用CRUD方法封裝到BaseService中,各業務Service通過繼承復用代碼。
完整示例代碼可訪問:GitHub倉庫鏈接 “`
(注:實際文章約2300字,此處為精簡展示。完整版應包含更詳細的代碼注釋、異常處理方案和性能對比數據)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。