Spring Boot和MyBatis-Plus怎么连接数据库
时间: 2024-05-01 16:19:41 浏览: 122
连接数据库需要进行以下步骤:
1. 在pom.xml文件中添加MyBatis-Plus和数据库驱动的依赖,例如:
```xml
<dependencies>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
</dependencies>
```
2. 在application.properties或application.yml文件中配置数据库连接信息,例如:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
```
3. 在Spring Boot主类上添加`@MapperScan`注解,指定MyBatis-Plus的mapper接口所在的包,例如:
```java
@SpringBootApplication
@MapperScan("com.example.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
4. 创建实体类和Mapper接口。实体类需要使用`@TableName`注解指定对应的数据库表名,Mapper接口需要继承`BaseMapper`,例如:
```java
@TableName("user")
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
// getter、setter方法省略
}
public interface UserMapper extends BaseMapper<User> {
}
```
至此,Spring Boot和MyBatis-Plus就已经成功连接数据库了。
阅读全文