Backend project connects to the database - add MyBatis dependency and check whether it is successful

1. Add Mybatis related dependencies in pom.xml

In a Spring Boot project, project dependencies are automatically loaded during compilation, and then the dependency packages are used.
You need to add Mybatis dependencies to the file in the root directory pom.xml
Insert image description here

<!-- Mybatis整合Spring Boot的依赖项 -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>
<!-- MySQL的依赖项 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>

Configuration purpose: Due to the automatic configuration of Spring Boot, when the mybatis dependency related to database programming is added, whether it is starting the project or executing any Spring Boot test, it will be tried Read the configuration information for connecting to the database. If the relevant configuration has not been added, it will cause startup failure/test failure

2. Add database connection configuration in the application.properties file

In the Spring Boot project, the file exists in the src/main/resources folder. This file is a configuration file that Spring Boot will automatically read. application.properties
Insert image description here

Inapplication.properties, it needs to be configured according to specific attribute names. After Spring Boot reads these specific configurations, it will automatically apply them!

# 添加连接数据库的配置:
spring.datasource.url=jdbc:mysql://localhost:3306/mall_pms?characterEncoding=utf-8&useUnicode=true&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root

3. Check whether the configuration of the connection database is correct

In the test class that already exists in the projectSmallApplicationTests, add the following code and execute the test:

    /**
     *  注意:导java.sql包中的接口
     */
    @Autowired
    DataSource dataSource;

    @Test
    void getConnection() throws Throwable {
    
    
        // 调用getConnection()时会连接数据库,则可以判断配置的连接信息是否正确
        dataSource.getConnection();
    }

Insert image description here
Insert image description here

4. Connection failed, possible problem

1. When the format of the configured spring.datasource.url value is incorrect, an error will occur:

Caused by: java.lang.IllegalArgumentException: URL must start with 'jdbc'

2. When the port number in the configurationspring.datasource.url is incorrect, an error will occur:

Caused by: java.net.ConnectException: Connection refused: connect

3.Failed to load driver class com.mysql.cj.jdbc.Driver异常

Create value and share it happily!

Guess you like

Origin blog.csdn.net/ly_xiamu/article/details/134685700