mybatis-plus如何使用Iservice
时间: 2024-06-11 13:10:35 浏览: 81
MyBatis-Plus中的IService是一个基础服务接口,提供了一些常见的数据操作方法。它是MyBatis-Plus提供的一种简化数据操作的方式,可以方便地进行CRUD操作。
使用IService需要先定义一个实体类,并且继承BaseEntity类,如:
```
public class User extends BaseEntity {
private Long id;
private String name;
private Integer age;
private String email;
// 省略getter/setter方法
}
```
然后定义一个继承IService的接口:
```
public interface IUserService extends IService<User> {
}
```
在接口中定义的方法会自动继承IService提供的方法,如:
```
public interface IUserService extends IService<User> {
List<User> selectList();
User selectById(Long id);
boolean insert(User user);
boolean updateById(User user);
boolean deleteById(Long id);
}
```
在实现类中,需要注入BaseMapper和IService,如:
```
@Service
public class UserServiceImpl extends ServiceImpl<BaseMapper<User>, User> implements IUserService {
@Autowired
private BaseMapper<User> userMapper;
@Autowired
private IUserService userService;
@Override
public List<User> selectList() {
return userMapper.selectList(null);
}
@Override
public User selectById(Long id) {
return userMapper.selectById(id);
}
@Override
public boolean insert(User user) {
return userMapper.insert(user) > 0;
}
@Override
public boolean updateById(User user) {
return userMapper.updateById(user) > 0;
}
@Override
public boolean deleteById(Long id) {
return userMapper.deleteById(id) > 0;
}
}
```
在使用时,只需要注入IUserService即可进行数据操作:
```
@RestController
public class UserController {
@Autowired
private IUserService userService;
@GetMapping("/users")
public List<User> getUsers() {
return userService.selectList();
}
@GetMapping("/users/{id}")
public User getUserById(@PathVariable Long id) {
return userService.selectById(id);
}
@PostMapping("/users")
public boolean addUser(@RequestBody User user) {
return userService.insert(user);
}
@PutMapping("/users")
public boolean updateUser(@RequestBody User user) {
return userService.updateById(user);
}
@DeleteMapping("/users/{id}")
public boolean deleteUserById(@PathVariable Long id) {
return userService.deleteById(id);
}
}
```
阅读全文