有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java序列化JSON中的许多映射

我正在用Spring JPA和Hibernate实现一个RESTful Web服务。我有一个简单的博客系统,有一个数据库表,用于帖子、标签和它们之间的依赖关系(多对多映射)。这是我的博客帖子实体:

@Entity
public class Post {

//...

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "posts_tags", joinColumns = {@JoinColumn(name = "post_id")},
        inverseJoinColumns = {@JoinColumn(name = "tag_id") })
    private List<Tag> tags;

//...
}

现在,如果我使用GET请求博客帖子,spring应用程序将返回以下json:

{
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/posts{?page,size,sort}",
      "templated" : true
    },
    "search" : {
      "href" : "http://localhost:8080/posts/search"
    }
  },
  "_embedded" : {
    "posts" : [ {
      "title" : "test title",
      "content" : "some test content",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/posts/1"
        },
        "tags" : {
          "href" : "http://localhost:8080/posts/1/tags"
        }
      }
    } ]
  },
  "page" : {
    "size" : 20,
    "totalElements" : 1,
    "totalPages" : 1,
    "number" : 0
  }
}

spring应用程序链接这些标记,而不是将它们包含在json repsonse中,这是我更喜欢的。有没有办法将多对多映射包含到json响应中?比如:

"_embedded" : {
    "posts" : [ {
        "title" : "test title",
        "content" : "some test content",
        "tags" : [ {
            "id" : 1,
            "name" : "tag1"
        }, {
            "id" : 2,
            "name" : "tag2"
        }]
    } ]
}

谢谢!


共 (0) 个答案