简体   繁体   中英

Migrate ResourceSupport to RepresentationModel

I have this code which I would like to migrate to latest Spring hateoas version. I tried this:

@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' and Cannot resolve method 'remove' in 'Links'

Do you know how I have to fix this issue?

I think that in the newer Spring Hateoas version you could achieve a similar result with this code:

@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;
  }
  ......................
}

I haven't tested it but probably the above code could be simplified like this:

@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;
  }
  ......................
}

Note that the main changes are related to the use of the methods provided in RepresentationModel and in the Links .

As I told, please, be aware that I haven't tested the code. My main concern has to do with the fact that this.getLinks().without(IanaLinkRelations.SELF); return a new Links instance and it may not replace in place the existing ones associated with the RepresentationModel , so you probably would need to merge the results. Please, take that into account.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM