Java:编译冲突:返回类型与HATEOAS ResourceSupport.getId不兼容

时间:2014-01-08 01:40:45

标签: java spring rest jpa spring-hateoas

所以我有这个HATEOAS实体。

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

我的实体的id类型为long,但HATEOAS的ResourceSupport要求getId返回一个Link。

实体具有Long id,因为db具有长id,并且它是持久化实体。如何使用HATEOAS实现此实体?

2 个答案:

答案 0 :(得分:7)

查看文档的“链接构建器”部分:

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

在那里,它描述了如何使用ControllerLinkBuilder使用单独的控制器类创建Link。您的User对象将实现Identifiable<Long>,如上页中的示例所示。

答案 1 :(得分:4)

您可以创建一个BeanResource bean,它扩展了ResourceSupport bean,如。

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

 @JsonUnwrapped
 private Object resorce;

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

 public Object getResorce() {
    return resorce;
 }

}

只需展开资源实例属性,以便BeanResource bean将像用户bean一样呈现json,以及ResourceSupport bean将呈现链接json对象,

之后你可以像这样创建汇编程序。

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

}

并在控制器中只附加包含用户bean的资源bean,如

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