Как получить данные родительской таблицы в ManyToOne в Spring Data Jpa? - PullRequest
0 голосов
/ 11 октября 2018

У меня есть две объектные модели Muscle и Exercise.Для одного Мускула будет много упражнений, и именно так они отображаются в проекте.Мой объект Muscle имеет свойство name, как мне его получить, когда я получаю объект Exercise?Я могу каким-то образом извлечь первый столбец в базе данных, который для первого упражнения содержит объект мышцы со свойством name, но со второго у него нет свойства name.

Это мой MuscleКласс

package com.fazla.exercise.model;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;


@Entity
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="id")
public class Muscle {

    @Id
//  @Column(unique = true, nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column
    private String name;

//  @JoinColumn(name="muscle")
//  @Column(nullable = true)
//  cascade is used so that for any changes in parent will change the child too 
    @OneToMany(mappedBy="muscle", orphanRemoval= false, fetch=FetchType.EAGER)

    private List<Exercise> exercises = new ArrayList<>();

    public Muscle() {

    }

    public Muscle(String name, List<Exercise> exercises) {
        super();
        this.name = name;
        this.exercises = exercises;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Exercise> getExercises() {
        return exercises;
    }

    public void setExercises(List<Exercise> exercises) {
        this.exercises = exercises;
    }

//  @Override
//  public String toString() {
//      return "Muscle [id=" + id + ", name=" + name + ", exercises=" + exercises + "]";
//  }



}

Это мой класс упражнений

package com.fazla.exercise.model;

import javax.persistence.CascadeType;
import javax.persistence.Column;
//import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToOne;

import com.fasterxml.jackson.annotation.JsonIdentityInfo;
import com.fasterxml.jackson.annotation.ObjectIdGenerators;

@Entity
//@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="id")
public class Exercise {
    @Id
    @Column(unique = true, nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    @Column
    private String name;

    @Column
    private String description;


    //As there will be many exercise under one muscle that is why manytoone
    //object references an unsaved transient instance - save the transient instance before flushing 
    //that is why need to add the cascading dependencies
//  (cascade = CascadeType.ALL)
//  @JoinColumn(name="muscle_id")
//  @JsonIgnore
//  @JoinTable(name="muscle")
    @ManyToOne
    @JoinColumn(name="muscle_id")

    private Muscle muscle;

    public Exercise() {

    }

    public Exercise(String name, String description, Muscle muscle) {
        super();
        this.name = name;
        this.description = description;
        this.muscle = muscle;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Muscle getMuscle() {
        return muscle;
    }

    public void setMuscle(Muscle muscle) {
        this.muscle = muscle;
    }

//  @Override
//  public String toString() {
//      return "Exercise [id=" + id + ", name=" + name + ", description=" + description + ", muscle=" + muscle + "]";
//  }



}

Вот так я получаю ответ JSON от API

[
    {
        "id": 1,
        "name": "Dumbbell Curl",
        "description": "Take a weight that let's you maintain the form",
        "muscle": {
            "id": 1,
            "name": "Biceps",
            "exercises": [
                {
                    "id": 1,
                    "name": "Dumbbell Curl",
                    "description": "Take a weight that let's you maintain the form",
                    "muscle": 1
                },
                {
                    "id": 2,
                    "name": "Barbell Curl",
                    "description": "Take a weight that let's you maintain the form",
                    "muscle": 1
                }
            ]
        }
    },
    {
        "id": 2,
        "name": "Barbell Curl",
        "description": "Take a weight that let's you maintain the form",
        "muscle": 1
    }
]

Я хочу, чтобы он ответилобратно со всем мышечным объектом во втором упражнении, а не только с «мышцей»: 1

1 Ответ

0 голосов
/ 11 октября 2018

Такое поведение вызвано @JsonIdentityInfo

Этот вопрос содержит больше информации.@JsonIdentityInfo используется для решения проблемы циклических ссылок.Без этого вы получите бесконечную рекурсию, поскольку каждая мышца будет содержать упражнение, которое будет содержать мышцу спины и т. Д., Вы получите точку.Вы также можете просмотреть другие подходы для решения проблемы циклических ссылок.

...