溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringCloud中怎么利用MyBatis-Plus實現CRUD

發布時間:2021-08-10 11:35:15 來源:億速云 閱讀:213 作者:Leah 欄目:大數據
# 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>

三、MyBatis-Plus基礎配置

1. 數據源配置

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

2. 主啟動類配置

添加@MapperScan注解掃描Mapper接口:

@SpringBootApplication
@MapperScan("com.example.mapper")
public class UserServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(UserServiceApplication.class, args);
    }
}

四、實體類與Mapper設計

1. 實體類定義

使用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;
}

2. Mapper接口開發

繼承MyBatis-Plus的BaseMapper獲得基礎CRUD能力:

public interface UserMapper extends BaseMapper<User> {
    // 自定義查詢方法
    @Select("SELECT * FROM sys_user WHERE age > #{age}")
    List<User> selectUsersOlderThan(Integer age);
}

五、核心CRUD實現

1. 插入操作(Create)

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    public boolean addUser(User user) {
        return userMapper.insert(user) > 0;
    }
}

2. 查詢操作(Read)

基礎查詢

// 根據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);

3. 更新操作(Update)

// 根據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);

4. 刪除操作(Delete)

// 物理刪除
userMapper.deleteById(1L);

// 邏輯刪除(需配置邏輯刪除字段)
userMapper.deleteById(1L); // 實際執行的是UPDATE語句

六、高級特性應用

1. 自動填充功能

實現MetaObjectHandler接口:

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
    }
}

2. 樂觀鎖實現

  1. 添加版本號字段并添加注解:
@Version
private Integer version;
  1. 配置插件:
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());

七、SpringCloud集成注意事項

1. 多數據源配置

在微服務場景下可能需要連接多個數據庫:

@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();
    }
}

2. Feign客戶端調用

在服務間調用時處理MyBatis-Plus的Page對象序列化問題:

@FeignClient(name = "user-service")
public interface UserClient {
    @PostMapping("/user/page")
    CommonResult<Page<User>> getUserPage(@RequestBody PageQuery query);
}

八、性能優化建議

  1. 批量操作:使用saveBatch()方法提升插入效率
  2. SQL打印控制:生產環境關閉mybatis-plus.configuration.log-impl
  3. 索引優化:為高頻查詢字段添加數據庫索引
  4. 二級緩存:合理使用MyBatis二級緩存

九、總結

通過本文的實踐,我們實現了: - SpringCloud與MyBatis-Plus的無縫整合 - 基礎CRUD操作的標準化實現 - 分頁查詢、邏輯刪除等企業級功能 - 微服務環境下的特殊配置處理

MyBatis-Plus的強大功能可以讓我們在SpringCloud微服務體系中減少約70%的SQL編寫工作量,同時保持代碼的可維護性和擴展性。

最佳實踐提示:建議將通用CRUD方法封裝到BaseService中,各業務Service通過繼承復用代碼。

完整示例代碼可訪問:GitHub倉庫鏈接 “`

(注:實際文章約2300字,此處為精簡展示。完整版應包含更詳細的代碼注釋、異常處理方案和性能對比數據)

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女