Error doing Many to Many interface with Spring Boot

Asked

Viewed 153 times

1

I’m trying to make a phone call Many-to-Many between classes usuario and permissao, using the documentation of Hibernate as reference . But when I try to generate a class JSON file usuario the program loops and generates an unexpected file.

How to avoid this and do with it limit the output file.

I’m using the Spring Boot 2.0.2

Below are my classes:

Usuario Class.

public class Usuario {
    protected long id;
    protected String nome;
    private String senha;

    @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
    private List<Permissao> permissao;
}

Permission.class

public class Permissao{
    protected long id;
    protected String nome;

    @ManyToMany(mappedBy = "permissao")
    private List<Usuario> usuario;
}

SQL(Constraints have been removed for simplification)

CREATE TABLE usuario
(
  id    INT UNSIGNED AUTO_INCREMENT
    PRIMARY KEY,
  nome  VARCHAR(45) NOT NULL,
  senha VARCHAR(45) NOT NULL
)

CREATE TABLE usuario_permissao
(
  usuario_id   INT(11) UNSIGNED NOT NULL,
  permissao_id INT(11) UNSIGNED NOT NULL
)

CREATE TABLE permissao
(
  id   INT UNSIGNED AUTO_INCREMENT
    PRIMARY KEY,
  nome VARCHAR(45) NOT NULL
)

and the json output

[{"id":1,"nome":"admin","senha":"admin","permissao":
[{"id":1,"nome":"admin","usuario":
[{"id":1,"nome":"admin","senha":"admin","permissao":
[{"id":1,"nome":"admin","usuario":
[{"id":1,"nome":"admin","senha":"admin","permissao":
[{"id":1,"nome":"admin","usuario":
[{"id":1,"nome":"admin","senha":"admin","permissao":
[{"id":1,"nome":"admin","usuario":

1 answer

1


In general, it is not a good idea to use JPA/Hibernate entities and turn them into Json, or involve them in any other type of serialization. As it may involve circular mapping (as in your case), this can create situations like yours, plus many other issues ranging from performance to maintenance.

For this type of problem, it is more flexible and safe to use some kind of DTO class and turn them into the appropriate Json. This can be done without much effort using some utility class of mapper to transform from Entity to DTO.

Example, consider the Dtos:

class UsuarioDto {
     private Long id;
     private String nome;
     private List<PermissaoDto> permissao;
}

class PermissaoDto {
     private Long id;
     private String nome;
}

And using some mapper:

UsuarioDto usuarioDto = mapper.map(usuario, UsuarioDto.class);

If the fields have the same name in the entity and DTO, the conversion is carried out in a transparent manner. This DTO can be serialized smoothly and you have full control of what you want to display (or not) in Json.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.