我有一个使用GSON库从这个Graph
类生成的JSON文件。
这是Graph类的代码:
public class Graph {
private List<Node> nodes;
private List<Link> links;
// Constructors, Getters and Setters
}
这是Node类的代码:
public class Node {
private String name;
private int group;
private Set<Link> linksForTarget = new HashSet<Link>(0);
private Set<Link> linksForSource = new HashSet<Link>(0);
// Constructors, Getters and Setters
}
这是Link类的代码:
public class Link {
private Integer idLink;
private Node nodeByTarget;
private Node nodeBySource;
// The two above 'nodeByTarget' and 'nodeBySource'
// are foreign keys to `Node` class
// Constructors, Getters and Setters
}
这是我想要生成的JSON文件:
{
"nodes":[
{"name":"Myriel","group":1},
{"name":"Napoleon","group":1},
{"name":"Mlle.Baptistine","group":2},
{"name":"Mme.Hucheloup","group":2}
],
"links":[
{"source":1,"target":0},
{"source":2,"target":0},
{"source":3,"target":1},
{"source":3,"target":2}
]
}
问题在于,当我从数据库中获取值并将它们解析为JSON(使用GSON工具)时,我得到的链接的源和目标比预期的大1(因为数据库的自动增量永远不会从0)所以我得到这样的东西:
{
"nodes":[
{"name":"Myriel","group":1},
{"name":"Napoleon","group":1},
{"name":"Mlle.Baptistine","group":2},
{"name":"Mme.Hucheloup","group":2}
],
"links":[
{"source":2,"target":1},
{"source":3,"target":1},
{"source":4,"target":2},
{"source":4,"target":3}
]
}
这对我不起作用!
现在想把我从数据库中获得的源和目标的值减少1。
我试过这段代码:
public static List<Link> listLinks() {
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
List<Link> links = session.createQuery("from Link").list();
List<Link> modLinks = new ArrayList<Link>();
int oldSource, newSource, oldTarget, newTarget;
Iterator<Link> itr = links.iterator();
while(itr.hasNext()) {
Link l = itr.next();
oldSource = l.getNodeBySource().getIdNode();
newSource = oldSource - 1;
l.getNodeBySource().setIdNode(newSource);
oldTarget = l.getNodeByTarget().getIdNode();
newTarget = oldTarget - 1;
l.getNodeByTarget().setIdNode(newTarget);
System.out.println(l.getNodeBySource().getIdNode() + " , " + l.getNodeByTarget().getIdNode());
modLinks.add(l);
}
session.close();
return modLinks;
}
但事情变得更糟,因为我得到了负面结果!
这是我从数据库中获取的所有数据的日志结果:
source : 0 , target : 1
source : -1 , target : 2
source : -2 , target : 3
source : -3 , target : 4
source : -4 , target : 5
source : 0 , target : 1
source : -1 , target : 2
source : -2 , target : 3
source : -3 , target : 4
source : 0 , target : 1
source : -1 , target : 2
source : -2 , target : 3
source : 0 , target : 1
source : -1 , target : 2
source : 0 , target : 1
source : 8 , target : 9
source : 7 , target : 10
source : 8 , target : 9
source : 11 , target : 12
source : 10 , target : 13
source : 9 , target : 14
source : 8 , target : 15
source : 7 , target : 16
source : 11 , target : 12
source : 10 , target : 13
source : 9 , target : 14
source : 8 , target : 15
source : 11 , target : 12
source : 10 , target : 13
source : 9 , target : 14
source : 11 , target : 12
source : 10 , target : 13
source : 11 , target : 12
source : 17 , target : 18
我做错了什么?我该如何解决?
谢谢!