mybatis-plus使用
时间: 2023-07-18 08:07:41 浏览: 57
MyBatis-Plus是一个开源的MyBatis增强工具,它在MyBatis的基础上封装了一些常用的CRUD操作,简化了开发,提高了效率。
下面是MyBatis-Plus的使用步骤:
1. 引入依赖
在项目的pom.xml文件中添加MyBatis-Plus依赖:
```xml
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
```
2. 配置数据源
在application.properties中配置数据源:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/db_test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
```
3. 创建实体类
创建实体类并添加注解,注解用于映射数据库表和字段:
```java
@Data
@TableName("user")
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
}
```
4. 创建Mapper
创建Mapper接口并继承BaseMapper,BaseMapper提供了一些常用的CRUD操作,无需手写SQL语句:
```java
public interface UserMapper extends BaseMapper<User> {
}
```
5. 使用Mapper
在Service中注入Mapper并使用其提供的方法进行数据库操作:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getById(Long id) {
return userMapper.selectById(id);
}
@Override
public boolean save(User user) {
return userMapper.insert(user) > 0;
}
@Override
public boolean updateById(User user) {
return userMapper.updateById(user) > 0;
}
@Override
public boolean removeById(Long id) {
return userMapper.deleteById(id) > 0;
}
}
```
以上就是MyBatis-Plus的使用步骤,它提供了很多便捷的操作,可以大大减少开发时间和精力。