Persistent resource return with Hibernate

6

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?

    
asked by anonymous 25.06.2018 / 18:55

1 answer

0

From what I understand you want to save the user passing the id of a new profile, is that right? If it is, the value of the name will always be null. @OneToOne by default is EAGER ( OneToOne documentation ), so it's no use uploading again because it will always load when the user entity loads. I will offer you some suggestions for improvement as you requested:

Suggestions for improvement:

1) Tip: Arrange the method name

     Perfil perfil = perfilDao.perfil(usuario.getPertil().getId()); //O que quer dizer perfil ??
     //Coloque alguma coisa mais clara, por exemplo
     Perfil perfil = perfilDao.recuperPerfil(usuario.getPertil().getId());

Method means an action, so the ideal would be to change the infinitive, instead of saving.

 @PostMapping
  public ResponseEntity<Usuario> **salvar**(@RequestBody Usuario usuario) {...

2) Tip: If it is a 1 to 1 relational, then there will always be a user and a profile, correct? Would not it be better to use @Embedded, why are their entities small? Here is the documentation: link

3) Tip: If it will always be 1 for 1, the ID MAY be the same, then use @MapsId Following documentation: link

4) Tip: Thinking objectively, I believe a user has a profile, but a profile can be tied to multiple users. For example: Maria (1) has the profile of Admistrador (1), Joao (2) also has the profile of Administrador (1). If you follow this form would greatly change your project, you would first register the Profile and then the user, and it would be a @ManyToOne relationship, which is also EAGER by default, and would probably solve your null problem.

5) Last suggestion: If you save the user and the profile together and the mapping is correct, then pass the following in JSON:

{
    "nome":"usuario novo",
    "perfil":{
        "id":1,
        "nome": "Administrador"
    }
}

This will probably resolve the null that is returning.

I suggest making the suggestions for numbers 1,2 and 4.

    
26.06.2018 / 02:29