spring hateoas 1.0
前言
因为在看spring实战第五版敲代码时候发现改组件已经更新,书中没改,旧方法已在新版本弃用
Resource
改为
EntityModel
变化
和原来用法位置一样,改了名而已
Resources
改为
CollectionModel
变化
和原来用法位置一样,改了名而已
ResourceSupport
改为
RepresentationModel
变化
使用方法和原来无差别
public class TacoModel extends RepresentationModel<TacoModel> {
@Getter
private final String name;
@Getter
private final Date createAt;
@Getter
private final List<Ingredient> ingredients;
public TacoModel(Taco taco) {
this.name = taco.getName();
this.createAt = taco.getCreatedAt();
this.ingredients = taco.getIngredients();
}
}
ResourceAssemblerSuppor
改为
RepresentationModelAssemblerSuppor
变化
使用起来和原先没什么太大差异,只是映射名称和方法名变了
public class TacoModelAssembler extends RepresentationModelAssemblerSupport<Taco, TacoModel> {
public TacoModelAssembler() {
super(DesignTacoApiController.class, TacoModel.class);
}
@Override
public TacoModel toModel(Taco taco) {
return createModelWithId(taco.getId(), taco);
}
@Override
protected TacoModel instantiateModel(Taco taco) {
return new TacoModel(taco);
}
}
public CollectionModel<TacoModel> recentTacos() {
PageRequest page = PageRequest.of(0, 12, Sort.by("createdAt").descending());
List<Taco> tacos = tacoRepository.findAll(page).getContent();
CollectionModel<TacoModel> recentCollectionModel = new TacoModelAssembler().toCollectionModel(tacos);
recentCollectionModel.add(
linkTo(methodOn(DesignTacoApiController.class).recentTacos())
.withRel("recents")
);
return recentCollectionModel;
}