将资源支持迁移到表示模型



我有这个代码,我想迁移到最新的Spring hateoas版本。我试过了:

@JsonInclude(Include.NON_NULL)
public class TransactionResource extends RepresentationModel {
@JsonProperty("id")
private UUID uuid;
public void setUuid(UUID uuid) {
// Remove the hateoas ID (self referential link) if exists
if (getId() != null) {
getLinks().remove(getId());
}
add(linkTo(methodOn(TransactionController.class).lookup(uuid, null))
.withSelfRel()
.expand());
this.uuid = uuid;
}
......................
}

I get error Cannot resolve method'getId' in 'TransactionResource'andCannot resolve method 'remove' in 'Links'

你知道我要怎么解决这个问题吗?

我认为在较新的Spring Hateoas版本中,您可以使用以下代码实现类似的结果:

@JsonInclude(Include.NON_NULL)
public class TransactionResource extends RepresentationModel {
@JsonProperty("id")
private UUID uuid;
public void setUuid(UUID uuid) {
// Remove the hateoas ID (self referential link) if exists
if (this.hasLink(IanaLinkRelations.SELF)) {
this.getLinks().without(IanaLinkRelations.SELF);
}
add(linkTo(methodOn(TransactionController.class).lookup(uuid, null))
.withSelfRel()
.expand());
this.uuid = uuid;
}
......................
}

我还没有测试过,但上面的代码可能可以简化成这样:

@JsonInclude(Include.NON_NULL)
public class TransactionResource extends RepresentationModel {
@JsonProperty("id")
private UUID uuid;
public void setUuid(UUID uuid) {
// Remove the hateoas ID (self referential link) if exists
this.getLinks().without(IanaLinkRelations.SELF);
add(linkTo(methodOn(TransactionController.class).lookup(uuid, null))
.withSelfRel()
.expand());
this.uuid = uuid;
}
......................
}

请注意,主要变化与RepresentationModelLinks中提供的方法的使用有关。

正如我所说,请注意我还没有测试代码。我主要担心的是this.getLinks().without(IanaLinkRelations.SELF);返回一个新的Links实例,它可能不会取代RepresentationModel相关的现有的,所以你可能需要merge的结果。请把这一点考虑进去。

最新更新