我使用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 来终止递归关系。
您认为这是一个很好的解决方案,还是有其他更实用的方法?谢谢