Good afternoon. I would like to understand how to solve the following question:
In the project I'm working on, Backend and Frontend are separated. To persist the data I am using Hibernate and to control the connection with the DB I have a filter that opens the connection at the beginning of the request and closes the same when returning the response.
The use case is: In the frontend the user creates a new user relating to a profile. There are already two profiles registered in the DB being:
1 - BASICO
2 - ADMINISTRADOR
User and Profile are represented by different classes:
User Class:
@Entity
public class Usuario{
@Id
private Long id;
private String nome;
@OneToOne
@JoinColumn(name="id_perfil")
private Perfil perfil;
}
Profile Class:
@Entity
public class Perfil{
@Id
private Long id;
private String nome;
}
Example of the UserController class:
public class UsuarioController{
@PostMapping
public ResponseEntity<Usuario> salva(@RequestBody Usuario usuario) {
usuarioDao.salva(usuario);
return new ResponseEntity<Usuario>(usuario, HttpStatus.CREATED);
}
}
Example of class UserDao - method to save:
public void salva(Usuario usuario) {
// estou utilizando esta estratégia para gerenciar a conexão no BD
EntityManager manager = JpaUtil.getEntityManager();
manager.persist(usuario);
}
The JSON received from Frontend to register user is:
{
"nome":"usuario novo",
"perfil":{
"id":1
}
}
The JSON returned from the Backend to Frontend is:
{
"nome":"usuario novo",
"perfil":{
"id":1
"nome":null
}
}
After the user finishes creating the new user on the screen, the application directs the user to the Users List screen. However, in the frontend when adding the new row containing the new user data in the list, the profile column will appear as: null - compatible with what is being returned in JSON.
What is good practice for this case ???
Backend also return the profile name in JSON, that is, before returning the User in the response, do the following in the controller class:?
change in UserController return - method to create new user
public class UserController {
@PostMapping
public ResponseEntity<Usuario> salva(@RequestBody Usuario usuario) {
Usuario usuario = usuarioDao.salva(usuario);
Perfil perfil = perfilDao.perfil(usuario.getPertil().getId());
usuario.setPerfil(perfil);
return new ResponseEntity<Usuario>(usuario, HttpStatus.CREATED);
}
}
Should Frontend make a new request by passing the created user ID, so that it receives the complete object?