【问题标题】:Spring Data JPA to deep and weird mappingSpring Data JPA 到深度和奇怪的映射
【发布时间】:2018-01-03 18:11:28
【问题描述】:

最近我正在尝试使用多对一和一对多创建 CRUD。我有以下奇怪的结果,我无法处理。

这是来自 /teams 的 JSON,我有什么

[
{
    "id": 3,
    "name": "team1",
    "footballers": [
        {
            "id": 12,
            "name": "karol",
            "age": 0,
            "team": {
                "id": 3,
                "name": "team1",
                "footballers": [
                    12,
                    {
                        "id": 13,
                        "name": "Pauluszka",
                        "age": 0,
                        "team": 3
                    }
                ]
            }
        },
        13
    ]
}
]

而我想要实现的是

[
{
    "id": 3,
    "name": "team1",
    "footballers": [
        {
            "id": 12,
            "name": "karol",
            "age": 0
         },
         {
           "id": 13,
           "name": "Pauluszka",
           "age": 1
        }
    ]
}

]

这是我的 Pojo 的

Footballer.java

...somecodehere
@ManyToOne
@JoinColumn(name="team_id")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class , property = "id")
private Team team;
...somecodehere

Team.java

...somecodehere
@OneToMany(mappedBy = "team")
@JsonIdentityInfo(
        generator = ObjectIdGenerators.PropertyGenerator.class,
        property = "id")
private List<Footballer> footballers;
...somecodehere

如果您能给我一些提示,我将不胜感激,我应该改变什么来实现我想要的。

【问题讨论】:

  • 问题是?您想知道如何生成一些 JSON? (在这种情况下,问题与 JPA 无关)或者您想知道如何保留该 Java 模型? (在这种情况下没有 JSON 相关性)
  • 问题是在我的情况下做错了什么,我正在实现这个奇怪的 json 而不是我想要的。
  • 好的,那么与 JPA API 无关。

标签: java json spring spring-data-jpa crud


【解决方案1】:

使用@JsonManagedReference@JsonBackReference

这里有例子http://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion

您可以使用@JsonView 注解来指定要在选定视图中序列化的字段。这将允许您按需省略 playerteam 属性。

【讨论】:

    猜你喜欢
    • 2015-04-11
    • 1970-01-01
    • 2019-08-12
    • 2016-04-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多