EN VI

Java - Creating multiple interfaces for handling different API operations Spring Boot?

2024-03-15 10:00:07
How to Java - Creating multiple interfaces for handling different API operations Spring Boot

I'm creating a REST API in Spring Boot and there are the following tables on the DB:

CREATE TABLE Question
(
    id              SERIAL,
    id_survey       INT,
    description     VARCHAR(1000)
    * Other fields *
);

CREATE TABLE QuestionChoice
(
    id          SERIAL,
    id_question INT,
    description VARCHAR(1000)
    * Other fields *
);

I have created their respective models, however I need something more flexible for handling different operations, for instance:

  1. Returning just a Question
  2. Returning a Question with a list of its QuestionChoices
  3. Creating a Question, not sending in the POST call its id, along with a list of its QuestionChoices missing the id_question field, since all of the relations will be linked after the call

So far I've been using the Question model for the first task. For the second and third, I don't know what should I do.

What practices are the best for handling situations such as this?

Solution:

  1. use different data objects for data persistence to the database, from the request object that the API uses.

e.g.

public class Question {
    private Long id;
    private Integer idSurvey;
    private String description;
}

for the database and

public class QuestionRequest {
    private Integer idSurvey;
    private String description;
    // plus choices
}

Then you write a Service class that expects the QuestionRequest, validates the data and creates Question and QuestionChoices and persists these in the database.

You can follow the same idea when return data from the API - query the database and then populate some Response object that holds different fields.


  1. to handle the two database tables, and whether to query one table or both... this is a big topic. Go look up "Spring Hibernate JPA, one-to-many mapping" - there are many books and tutorials, e.g. https://attacomsian.com/blog/spring-data-jpa-one-to-many-mapping
Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login