mybatis-plus教程
时间: 2023-09-23 18:13:31 浏览: 51
MyBatis-Plus是一个MyBatis的增强工具,它在MyBatis的基础上增加了很多实用的功能,使得开发更加高效、便捷。
以下是MyBatis-Plus的使用教程:
1. 引入MyBatis-Plus依赖
在项目的pom.xml文件中引入MyBatis-Plus的依赖:
```
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
```
2. 配置MyBatis-Plus
在application.properties文件中配置MyBatis-Plus的相关配置:
```
# 数据库配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root
# MyBatis-Plus配置
mybatis-plus.mapper-locations=classpath:mapper/*.xml
mybatis-plus.type-aliases-package=com.example.entity
```
3. 创建实体类
使用MyBatis-Plus需要创建实体类,并且在实体类中使用注解来映射数据库表和字段:
```
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("user")
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
}
```
4. 创建Mapper接口
使用MyBatis-Plus需要创建Mapper接口,并且让该接口继承BaseMapper接口:
```
public interface UserMapper extends BaseMapper<User> {
}
```
5. 使用MyBatis-Plus进行CRUD操作
MyBatis-Plus提供了很多实用的方法来进行CRUD操作,如save、updateById、removeById等方法。使用起来非常方便,如下所示:
```
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public void saveUser(User user) {
userMapper.insert(user);
}
@Override
public void updateUser(User user) {
userMapper.updateById(user);
}
@Override
public void deleteUser(Long id) {
userMapper.deleteById(id);
}
@Override
public User getUserById(Long id) {
return userMapper.selectById(id);
}
@Override
public List<User> getAllUsers() {
return userMapper.selectList(null);
}
@Override
public List<User> getUsersByName(String name) {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.eq("name", name);
return userMapper.selectList(wrapper);
}
}
```
以上就是MyBatis-Plus的使用教程,希望对你有所帮助。