春天的HATEOAS。嵌入式资源+ CRUD的能力吗?

时间:2015-06-23 20:15:23

标签: json spring spring-data-jpa hateoas spring-hateoas

embedded resources的典型情况:

@Entity @Data
class Item {
    id, name
    ...
    @ManyToOne
    @JoinColumn(name="status", referencedColumnName="ID")
    private Status status;
}

@Entity @Data
class Status {
    id, name
    ...
    @JsonIgnore //break infinite reference loop during serialization
    @OneToMany(mappedBy="status")
    private List<Item> items;
}

我希望在项目 JSON

中包含状态对象,而不是在项目JSON中链接到状态ID
        {
            "itemName": "abc",
              ... ,
            "status": {
                "statusName":"ACTIVE",
                  ...
            }
            "_links": {
              ...
            }
        }

我管理嵌入 任何 以下内容:

  • 项目状态属性标记为@RestResource(exported = false)
    @Entity @Data
    class Item {
        ...
        @RestResource(exported=false) // <-- HERE
        @ManyToOne
        @JoinColumn(name="status", referencedColumnName="ID")
        private Status status;
  • 标记状态 repo接口@RepositoryRestResource(...,exported = false)
    @RepositoryRestResource(collectionResourceRel="statuses", path="status", exported=false)
    public interface StatusRepository extends JpaRepository<Status, String>
  • 删除状态实体的存储库
    // DELETED
    @RepositoryRestResource
    public interface StatusRepository extends JpaRepository<Status, String>{}

问题:

其中任何一个将状态嵌入到项目JSON中,就像我想要的那样,但是我无法再访问Status Repository来获取Status对象的ID或对其进行任何CRUD。

如何通过网址在父项JSON中嵌入状态并仍处于CRUD状态?

1 个答案:

答案 0 :(得分:0)

我按如下方式实施:

click.bs.dropdown
show.bs.dropdown
shown.bs.dropdown

存在两个实体的存储库,因此可以在状态实体上执行CRUD

@Entity @Data
class Item {
    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "uuid2")
    String id;
    String name

    @RestResource(exported = false) // <---- ADDED
    @ManyToOne
    @JoinColumn(name="status", referencedColumnName="ID")
    private Status status;
}

@Entity @Data
class Status {
    @Id
    @GeneratedValue(generator = "uuid2")
    @GenericGenerator(name = "uuid2", strategy = "uuid2")
    String id
    String name

    // <-------- DELETED REFERENCE TO PARENT OBJECT
    //@OneToMany(mappedBy="status")
    //private List<Item> items;
}

对于后代,我会留在这里。

为方便起见:

1)JSON中实体的​​暴露ID

@RepositoryRestResource(collectionResourceRel="items", path="items")
public interface StatusRepository extends JpaRepository<Item, String>
{}

@RepositoryRestResource(collectionResourceRel="statuses", path="statuses")
public interface StatusRepository extends JpaRepository<Status, String>
{}

所以获取项目列表如下:

/**
 * Exposing Ids as properties for entities specified
 */
@Configuration
public class ExposeIdConfig extends RepositoryRestMvcConfiguration {
  @Override
  protected void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) {
    config.exposeIdsFor(Item.class, Status.class);
  }
}