您好,登录后才能下订单哦!
# 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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。