SpringBoot+Mybatis-Plus实现增删改查--项目阶段
在Spring Boot项目中使用MyBatis-Plus实现增删改查的基本步骤如下:
- 添加依赖到
pom.xml
:
<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- MyBatis-Plus Starter -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.x.x</version>
</dependency>
<!-- 数据库驱动,以MySQL为例 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
- 配置
application.properties
或application.yml
:
spring.datasource.url=jdbc:mysql://localhost:3306/数据库名?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=数据库用户名
spring.datasource.password=数据库密码
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
- 创建实体类:
import com.baomidou.mybatisplus.annotation.TableName;
@TableName("表名")
public class Entity {
// 字段...
}
- 创建Mapper接口:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface EntityMapper extends BaseMapper<Entity> {
// 可以添加自定义方法
}
- 在Spring Boot启动类上添加
@MapperScan
注解扫描Mapper:
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("你的mapper包的路径")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
- 使用MyBatis-Plus提供的CRUD方法进行操作:
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class EntityService extends ServiceImpl<EntityMapper, Entity> {
// 使用MyBatis-Plus提供的CRUD方法
}
- 在你的控制器中注入
EntityService
并调用方法:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/entity")
public class EntityController {
@Autowire
评论已关闭