9

だから私はこの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();
    }
}  

私のエンティティには long 型の ID がありますが、HATEOAS の ResourceSupport では getId が Link を返す必要があります。

データベースには長い ID があり、永続化されたエンティティであるため、エンティティには長い ID があります。このエンティティを HATEOAS で実装するにはどうすればよいですか?

4

2 に答える 2

7

ドキュメントの「Link Builder」セクションを確認してください。

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

そこでは、 を使用して、別のコントローラ クラスを使用しControllerLinkBuilderて を作成する方法が説明されています。Link上記のページの例が示すように、Userオブジェクトは を実装します。Identifiable<Long>

于 2014-01-08T01:49:21.520 に答える
5

ResourceSupport Bean のように拡張する BeanResource Bean を 1 つ作成できます。

@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);
}
于 2015-04-24T07:19:21.893 に答える