I have found many articles about the circular reference with Gson, but I can\'t find an elegant solution.
As I know, some solutions is:
Since Gson doesn't properly handle circular references, and in some cases you may need to call the parent entity from its child, you can do this. Say we have:
@Entity
@Table(name = "servers_postgres")
public class PostgresServer implements Serializable {
public PostgresServer() {
this.tables = new ArrayList<>();
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_server")
private Integer serverId;
@OneToMany(orphanRemoval = true, mappedBy = "server", fetch = FetchType.EAGER)
@Cascade(org.hibernate.annotations.CascadeType.ALL)
private List tables;
@Column(length = 250)
private String serverAddress;
@Column(length = 250)
private String name;
}
and
@Entity
@Table(name = "postgres_tables")
public class PostgresTable implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_table")
private Integer tableId;
@Column(length = 250)
private String name;
@ManyToOne()
@JoinColumn(name = "id_server", foreignKey = @ForeignKey(name = "fk_postgres_tables"))
private PostgresServer server;
}
In this case, you may need to get a PostgresServer reference from a PostgresTable entity. So, instead of excluding PostgresServer from serialization, you simply set its List of tables to null. For example:
//Assuming a List...
postgresTables.forEach(postgresTable -> postgresTable.getServer().setTables(null));
This is how i solve circular references with Gson. Hope that helps someone.