代码之家  ›  专栏  ›  技术社区  ›  iwannabeprogrammer

Spring数据JPA到深度和怪异的映射

  •  2
  • iwannabeprogrammer  · 技术社区  · 7 年前

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

    这是来自/团队的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

    足球运动员Java语言

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

    团队Java语言

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

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

    1 回复  |  直到 7 年前
        1
  •  0
  •   Antoniossss    7 年前

    使用 @JsonManagedReference @JsonBackReference

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

    您可以使用 @JsonView 注释,指定要在选定视图中序列化的字段。这将允许您 team 的属性 player 按需提供。