'Return id of Many-To-One relation in Java Spring rest api

I have 2 models: Student and Teacher. Teacher has One-To-Many relation with Student, Student has Many-To-One with teacher. I want to build API what gonna have in response just id of teacher, in request just id of teacher too. How can i do so?

[
  {
    "id": 0,
    "name": "string",
    "grade": "int32",
    "teacher": 0,
  }
]

And thisrequest to the POST method

{
  "name": "string",
  "grade": "int",
  "teacher": 0,
}

But now I have this example data (from Swagger) to POST method:

{
  "name": "string",
  "grade": "int",
  "teacher": {
    "id": 0,
    "name": "string",
    "surname": "string",
    "students": [
      {
        "id": 0,
        "name": "string",
        "grade": "int",
        "teacher": "string"
      }
    ]
  },
}

Models:

@Entity
@Getter
@Setter
@NoArgsConstructor
public class Teacher {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    private String surname;

    @OneToMany(orphanRemoval = true, mappedBy = "author")
    private List<Student> students;

    public Teacher(TeacherRequest request) {
        this.name = request.getName();
        this.surname = request.getSurname();
        this.students = new ArrayList<Student>();
    }
}



@Entity
@Getter
@Setter
@NoArgsConstructor
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    private int grade;

    @ManyToOne(fetch = FetchType.LAZY)
    @OnDelete(action = OnDeleteAction.CASCADE)
    private Teacher teacher;

    public Book(BookRequest request) {
        this.name = request.getName();
        this.grade = request.getGrade();
        this.teacher = request.getTeacher();
    }
}

also i have there bodies for Stundent:

@Getter
@Setter
public class StudentRequest {
    private String name;
    private int grade;
    private Teacher Teacher;
}

@Getter
public class StudentResponse {

    private final long id;
    private final String name;
    private final int grade;
    private final Long teacher;

    public BookResponse(Book b) {
        this.id = b.getId();
        this.name = b.getName();
        this.grade = b.getGrade();
        this.teacher = b.getAuthor().getId();
    }
}


Solution 1:[1]

If you specifically only want the id or only one of the entity fields to be returned then, you can use @JsonIdentityInfo and @JsonIdentityReference annotations to get the job done.

Reference: https://stackoverflow.com/a/65389727/14011502

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Harshank Bansal