在我的项目

时间:2017-11-06 07:40:31

标签: spring spring-mvc spring-data spring-data-jpa

问题是:我应该在哪里以适当的方式使用Spring MVC声明新的排序或新的分页?

我正在阅读很多示例用法,其中大多数只是在“可运行”(@SpringBootApplication)类中,但我认为这不是一个好习惯。 (我决定把它放在我的控制器中,但我不是百分之百确定它。也许整个逻辑应该在服务中并且只是清除@RequestMapping应该在Controller中?

现在项目结构如下:

ProjectStructure

我不确定我的代码是否重要,但你可以在下面查看。

@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);

}

1 个答案:

答案 0 :(得分:1)

尝试为分页和排序创建弹簧数据规范

点击here了解更多如何创建规范

的内容