在JSON中序列化ManyToMany映射

时间:2015-01-11 20:20:53

标签: java json spring hibernate jpa

我正在使用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 个答案:

没有答案