spring boot使用mybatisplus访问mysql的配置流程
    		       		warning:
    		            这篇文章距离上次修改已过423天,其中的内容可能已经有所变动。
    		        
        		                
                在Spring Boot中使用MyBatis-Plus访问MySQL的基本配置步骤如下:
- 在pom.xml中添加依赖:
<!-- Spring Boot Starterparent,包含了自动配置的功能,用于快速集成Spring生态系统中的各种技术 -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.1.RELEASE</version>
    <relativePath/>
</parent>
 
<!-- Spring Boot Starter Web,包含了Tomcat服务器,Spring MVC等 -->
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
 
    <!-- MyBatis-Plus Starter -->
    <dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.4.0</version>
    </dependency>
 
    <!-- MySQL Connector -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
</dependencies>- 在application.properties或application.yml中配置数据库信息:
# application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
 
# 如果使用application.yml
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/your_database?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: yourpassword
    driver-class-name: com.mysql.cj.jdbc.Driver- 在Spring Boot启动类上添加@MapperScan注解,指定Mapper接口所在的包:
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
@MapperScan("com.yourpackage.mapper") // 指定Mapper接口所在包
public class YourApplication {
    public static void main(String[] args) {
        SpringApplication.run(YourApplication.class, args);
    }
}- 创建Mapper接口并使用MyBatis-Plus提供的CRUD方法:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import com.yourpackage.entity.YourEntity;
 
@Mapper
public interface YourEntityMapper extends BaseMapper<YourEntity> {
    // MyBatis-Plus会自动提供CRUD方法
}- 实体类对应数据库表:
import com.baomidou.mybatisplus.an
评论已关闭