Recently I had to implement a RESTful service which had to have a CRUD interface for storing entities with circular dependencies given as JSON. Usually if you have for example an object like this:
"graph": {
"nodes": [{"name":"n1"}, {"name":"n2"}],
"transitions": [{"source": {"name":"n1"}, "target": {"name":"n2"}]
}
and having these Java classes:
@Entity
class Graph {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
long id = 0;
List<Node> nodes = new ArrayList<Node>();
List<Transition> transitions = new ArrayList<Transition>();
}
@Entity
class Node {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
long id = 0;
String name = "";
}
@Entity
class Transition {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
long id = 0;
Node source;
Node target;
}
the nodes would be deserialized into 4 Java objects and therefore storing with different ids in the database. If you want instead referencing inside the JSON string the already defined nodes you have to add the @JsonIdentityInfo above the entities.
@JsonIdentityInfo(generator=ObjectIdGenerators.IntSequenceGenerator.class, property="@id")
@Entity
class Node {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
long id = 0;
String name = "";
}
After that you can define your references by using the id you used for nodes and the transitions will have references to the correct nodes.
"graph": {
"nodes": [{"@id":"1", "name":"n1"}, {"@id":"2", "name":"n2"}],
"transitions": [{"source": "1", "target": "2"]
}
0 Kommentare:
Kommentar veröffentlichen