小编典典

删除双向递归关系的最简单方法?

java

我使用Gson
库将Java对象转换为Json响应…问题是,在JPA请求之后,由于与其他实体的递归关系,无法转换从DB检索到的对象:

public class Gps implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @Column(name = "IMEI", nullable = false, length = 20)
    private String imei;
    //some code here...
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "gpsImei", fetch = FetchType.LAZY)
    private List<Coordonnees> coordonneesList;


public class Coordonnees implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "IDCOORDONNEES", nullable = false)
    private Integer idcoordonnees;
    //some code here...
    @JoinColumn(name = "GPS_IMEI", referencedColumnName = "IMEI", nullable = false)
    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    private Gps gpsImei;

我的源代码:

  EntityManagerFactory emf=Persistence.createEntityManagerFactory("JavaApplication21PU");
  GpsJpaController gjc=new GpsJpaController(emf);

  Gps gps=gjc.findGps("123456789012345");

  for(int i=0;i<gps.getCoordonneesList().size();i++){
   gps.getCoordonneesList().get(i).setGpsImei(null);
  }

  Gson gson=new Gson();
  String json=gson.toJson(gps);//convert to json response

  System.out.println(json);

如您在这里看到的,我做了:

   for(int i=0;i<gps.getCoordonneesList().size();i++){
     gps.getCoordonneesList().get(i).setGpsImei(null);
   }

只是通过为coordonneesList中的每个GPS对象设置null来消除递归关系。

您认为这是一个很好的解决方案,或者还有其他更实用的方法吗?谢谢


阅读 292

收藏
2020-09-16

共1个答案

小编典典

有一个名为GraphAdapterBuilder的Gson扩展,它可以序列化包含循环引用的对象。这是来自相应测试用例的非常简化的示例:

Roshambo rock = new Roshambo("ROCK");
Roshambo scissors = new Roshambo("SCISSORS");
Roshambo paper = new Roshambo("PAPER");
rock.beats = scissors;
scissors.beats = paper;
paper.beats = rock;

GsonBuilder gsonBuilder = new GsonBuilder();
new GraphAdapterBuilder()
    .addType(Roshambo.class)
    .registerOn(gsonBuilder);
Gson gson = gsonBuilder.create();
System.out.println(gson.toJson(rock));

打印:

{
  '0x1': {'name': 'ROCK', 'beats': '0x2'},
  '0x2': {'name': 'SCISSORS', 'beats': '0x3'},
  '0x3': {'name': 'PAPER', 'beats': '0x1'}
}

注意,GraphAdapterBuilder类 包含在gson.jar中。如果要使用它,则必须手动将其复制到项目中。

2020-09-16