ServiceDemo

增加(Create)

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public UserDTO createUser(UserDTO userDTO) {
        User user = new User();
        // 将UserDTO的属性设置到User对象中
        // ...
        userRepository.save(user);
        return userDTO;
    }

}

删除(Delete)

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public void deleteUser(Long id) {
        User user = userRepository.findById(id).orElse(null);
        if (user != null) {
            userRepository.delete(user);
        }
    }

}

修改(Update)

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public UserDTO updateUser(UserDTO userDTO) {
        User user = userRepository.findById(userDTO.getId()).orElse(null);
        if (user != null) {
            // 将UserDTO的属性设置到User对象中
            // ...
            userRepository.save(user);
            return userDTO;
        } else {
            return null;
        }
    }

}

查询(Retrieve)

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public UserVO getUserById(Long id) {
        User user = userRepository.findById(id).orElse(null);
        if (user != null) {
            return new UserVO(user); // 将User对象转换为UserVO对象,并返回
        } else {
            return null;
        }
    }

}

 分页查询(Pageable)

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public Page<UserVO> getUserPage(Pageable pageable) {
        Page<User> userPage = userRepository.findAll(pageable);
        List<UserVO> userVOS = userPage.getContent().stream()
                .map(UserVO::new) // 将User对象转换为UserVO对象
                .collect(Collectors.toList());
        return new PageImpl<>(userVOS, pageable, userPage.getTotalElements());
    }

}

 

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    
    public Page<UserVO> findUsersByPage(PageDTO pageDTO) {
        Pageable pageable = pageDTOToPageRequestConverter.convert(pageDTO);
        Page<User> userPage = userRepository.findAll((Pageable) pageable);
        List<UserVO> userVOS = userPage.getContent().stream().map(user -> userToUserVO(user)).collect(Collectors.toList());
        return new SimplePage(userVOS, userPage.getNumber(), userPage.getSize());
    }
}

 

posted @ 2023-09-01 11:44  平小宅  阅读(6)  评论(0编辑  收藏  举报