问题是:我应该在哪里以适当的方式使用Spring MVC声明新的排序或新的分页?
我正在阅读很多示例用法,其中大多数只是在“可运行”(@SpringBootApplication)类中,但我认为这不是一个好习惯。 (我决定把它放在我的控制器中,但我不是百分之百确定它。也许整个逻辑应该在服务中并且只是清除@RequestMapping应该在Controller中?
现在项目结构如下:
我不确定我的代码是否重要,但你可以在下面查看。
@RestController
public class PhoneController {
@Autowired
private PhoneService phoneService;
@Autowired
private PhoneRepository phoneRepository;
@RequestMapping(method = RequestMethod.GET, value = "/phones")
public List<Phone> getAllPhones() {return phoneService.getAllPhones();}
@RequestMapping(method = RequestMethod.GET, value = "/phones/{id}")
public Phone getPhone(@PathVariable Long id){return phoneService.getPhone(id);}
@RequestMapping(method = RequestMethod.POST, value = "/phones/{id}")
public void addPhone(@RequestBody Phone phone){
phoneService.addPhone(phone);
}
@RequestMapping(method = RequestMethod.PUT, value = "/phones/{id}")
public void updatePhone(@RequestBody Phone phone, @PathVariable Long id){phoneService.updatePhone(id, phone);}
@RequestMapping(method = RequestMethod.DELETE, value = "/phones/{id}")
public void deletePhone(@PathVariable Long id){ phoneService.deletePhone(id);}
//sorting...
@RequestMapping(method = RequestMethod.GET, value = "phones/year/{temp}")
public List<Phone> getPhoneByYearOfReleaseGreaterThan(@PathVariable Integer temp){
Sort sort = new Sort(new Sort.Order(Sort.Direction.ASC, "brand"));
List<Phone> phones = phoneRepository.findByYearOfReleaseGreaterThan(temp, sort);
for(Phone p: phones){
System.out.println(p);
}
return phones;
}
//pagination...
@RequestMapping(method = RequestMethod.GET, value = "phones/quarter/{temp}")
public List<Phone> getPhoneByQuarterOfRelease(@PathVariable String temp){
Sort sort = new Sort(new Sort.Order(Sort.Direction.ASC, "brand"));
Pageable pageable = new PageRequest(0, 5, sort);
List<Phone> phones = phoneRepository.findByQuarterOfRelease(temp, pageable);
for (Phone p : phones) {
System.out.println(p);
}
return phones;
}
}
这是我的PhoneRepistory:
public interface PhoneRepository extends CrudRepository<Phone, String> {
Phone findById(Long id);
@Transactional
Phone deleteById(Long id);
//sorting...
List<Phone> findByYearOfReleaseGreaterThan(Integer yearOfRelease, Sort sort);
//pagination...
List<Phone> findByQuarterOfRelease(String quarterOfRelease, Pageable pageable);
}