Error when making Many to Many relation with Spring Boot

1

I am trying to make a Many-to-Many link between the usuario and permissao classes, using the hibernate as a reference. But when I try to generate a JSON file of class usuario the program loops and generates an unexpected file.

How to avoid this and make it limit the output file.

I'm using Spring Boot 2.0.2

Below are my classes:

User.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":
    
asked by anonymous 19.05.2018 / 00:21

1 answer

1

In general, it is not a good idea to use JPA / Hibernate entities and transform them into Json, or wrap them in any other type of serialization. Because it can involve circular mappings (as in your case), this can create situations like yours, as well as 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 make them into the appropriate Json. This can be done without much effort using some utility class 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 performed transparently. This DTO can be serialized smoothly and you have full control of what you want to display (or not) in Json.

    
27.07.2018 / 18:16