I am currently developing a full-stack web application as a hobby project.
My tech stack is:
- MySql Database
- SpringBoot RestApi backend with JPA for the database interaction
- Vue frontend
I have already modelled the database and created jpa entities for all the tables in the database. The data model includes some bi-directional relationships (many to many relationships). I then started creating some API Endpoints for the frontend to interact with, but I have some problems with deciding how I want the data to be serialized and sent to the frontend.
In most of the tutorials and examples the objects that directly resemble the database objects are serialized and then sent to the frontend. But I dont want that, mainly because of the bi-directional relationships which create unserializable recursions, but also because not all the data of an object from the database is meant to be sent to the frontend.
So I want to know how the separation/conversion between the database(jpa) objects and the objects that are serialized and then sent to the frontend is usually achieved.
I had some ideas, but I dont know how feasible they are in the real world:
Idea 1: Create separate frontend classes of all entities which only include the data which has to be sent to the frontend. But this possibly creates additional problems because of the continuous conversion between classes in every request/answer.
Idea 2: Only send the "raw" object with all relations only as Ids, and just block all the "unwanted" data from serialization. In this case the frontend now has to do way more requests to the backend in order to resolve all those ids to the required data.
CodePudding user response:
Idea 1 is exactly how it is usually done. The "frontend classes" as you called them are usually called Data Transfer Objects (DTOs) which are essentially "views" of the data stored in the DB tailored specifically for effectiveness of transfer from backend to frontend (via aggregation of multiple related entities) and ease of use (display) by the frontend.
The problem of conversion is a known one and is quite successfully solved by so called "mappers" that allow for (semi-)automatic conversion between DB entities and DTOs. One great example of such a mapper is MapStruct
(https://mapstruct.org/documentation/stable/reference/html/) which nicely integrates with Spring and Lombok and has support in IntelliJ Idea.