mybatis-plus怎么连接数据库
时间: 2023-08-16 20:25:39 浏览: 188
MyBatis-Plus是一个基于MyBatis的极简、高性能、增强的ORM框架,可以快速、便捷地进行数据库操作。连接数据库的具体步骤如下:
1. 引入mybatis-plus的依赖。在Maven项目中,在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>x.x.x</version>
</dependency>
```
其中,x.x.x表示mybatis-plus的版本号。
2. 配置数据源。在application.yml或application.properties文件中添加数据源配置,如下所示:
```
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
```
其中,spring.datasource.driver-class-name表示数据库驱动程序的类名,spring.datasource.url表示数据库的连接URL,spring.datasource.username表示数据库的用户名,spring.datasource.password表示数据库的密码。
3. 配置MyBatis-Plus。在application.yml或application.properties文件中添加MyBatis-Plus的配置,如下所示:
```
mybatis-plus.mapper-locations=classpath:/mapper/*.xml
mybatis-plus.type-aliases-package=com.example.entity
```
其中,mybatis-plus.mapper-locations表示mapper文件的位置,mybatis-plus.type-aliases-package表示实体类所在的包。
4. 编写mapper接口。在mapper接口中使用MyBatis-Plus的注解来进行数据库操作,如下所示:
```
@Repository
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
```
其中,@Repository和@Mapper注解分别表示这是一个Spring的Repository和MyBatis的Mapper,UserMapper继承BaseMapper<User>,即可直接使用MyBatis-Plus提供的CRUD方法。
5. 在Service中调用mapper接口。在Service中注入mapper接口的实例,即可调用其中的方法进行数据库操作,如下所示:
```
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getUserById(Long id) {
return userMapper.selectById(id);
}
}
```
其中,@Autowired注解表示自动注入UserMapper的实例,selectById方法是MyBatis-Plus提供的查询方法。
至此,使用MyBatis-Plus连接数据库的步骤就完成了。需要注意的是,在使用MyBatis-Plus时,可以大大简化数据库操作,但是也需要注意数据库的安全性,比如避免SQL注入等安全漏洞。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![jar](https://img-home.csdnimg.cn/images/20210720083455.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)