Question

So I have this HATEOAS entity.

@Entity
@Table(name="users")
public class User extends ResourceSupport {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="id")
    private long id;

    public User() {

    }

    public Long getId() {
    return new Long(id);
    }

    public void setId(Long id) {
    this.id = id.longValue();
    }
}  

My entity has an id of type long, but HATEOAS's ResourceSupport requires that getId return a Link.

The entity has a Long id because the db has a long id, and it is a persisted entity. How can I implement this entity with HATEOAS?

Was it helpful?

Solution

Check out the "Link Builder" section of the documentation:

http://docs.spring.io/spring-hateoas/docs/current/reference/html/#fundamentals.obtaining-links.builder

There, it describes how to use a ControllerLinkBuilder to create the Link using a separate controller class. Your User Object would implement Identifiable<Long>, as the example in the page above shows.

OTHER TIPS

You can create one BeanResource bean which extends ResourceSupport bean like.

@JsonIgnoreProperties({ "id" })
public class BeanResource extends ResourceSupport {

 @JsonUnwrapped
 private Object resorce;

 public Resource(Object resorce) {
    this.resorce = resorce;
 }

 public Object getResorce() {
    return resorce;
 }

}

just Unwrap resource instance property so that BeanResource bean will render json like user bean along with ResourceSupport bean will render link json object,

after that you can create assembler like this.

public class UserAssembler extends ResourceAssemblerSupport<User, BeanResource> {

public UserAssembler() {
    super(User.class, BeanResource.class);
}

@Override
public Resource toResource(User user) {
    Resource userResource = new Resource(user);
    try {
        Link selfLink = linkTo(
                methodOn(UserController.class).getUser(user.getId()))
                .withSelfRel();
        userResource.add(selfLink);

    } catch (EntityDoseNotExistException e) {
        e.printStackTrace();
    }
    return userResource;
}

}

and in controller just attach Resource bean which contains user bean like

@RequestMapping(value = "/user/{userId}", method = RequestMethod.GET)
public ResponseEntity<Resource> getUser(@PathVariable String userId)
        throws EntityDoseNotExistException {
    User user = userService.getUser(userId);
    Resource userResource = userAssembler.toResource(user);
    return new ResponseEntity<Resource>(userResource, HttpStatus.OK);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top