08-通用Service接口

MP也为我们提供了Service层的实现,我们只需要编写一个接口,继承IService, 并创建一个接口实现类继承ServiceImpl,即可使用

基本使用

改造前

定义接口

public interface UserService {
	List<User> getUserList();
}

定义实现类

@Service
public class UserServiceImpl implements UserService {
    @Autowried
    private UserMapper userMapper;

    public List<User> getUserList() {
        userMapper.selectList(null);
    }
}

改造后

定义接口

public interface UserService extends IService<User> {

}

定义实现类
ServiceImpl<mapper对象, 实现类>
image.png

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>implements UserService {
}

测试

@SpringBootTest
public class ServiceTest {
    @Autowired
    private UserService userService;

    @Test
    void testService() {
        List<User> list = userService.list(null);
        list.forEach(System.out::println);
    }
}

自定义方法

接口

public interface UserService extends IService<User> {
    User findList();
}

实现类

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public User findList() {
        UserMapper userMapper = getBaseMapper();
        return userMapper.selectById(3L);
    }
}

测试类

    @Test
    void testService1() {
        User user = userService.findList();
        System.out.println(user);
    }
posted @ 2022-10-31 10:17  ゐ叶う枫ゆ  阅读(104)  评论(0编辑  收藏  举报