在我的java代码中,我创建了一个树,其中树中的节点类型为 Node。该节点具有类型 Node 的名称,属性和子节点。我正在使用db4o来存储树。我只是通过存储树的根节点来做到这一点。但是,我发现db4o不存储对象节点的所有子节点。当我从数据库中检索根并遍历树时,我只能遍历树的3个级别。似乎较低级别的子节点丢失了。有人可以帮助我,所以我不会丢失任何节点吗?谢谢。
以下是我的代码:
Node node1= new Node("root","this is the root",new ArrayList<Node>());
Node node2= new Node("zaid","123",new ArrayList<Node>());
Node node3= new Node("saad","999",new ArrayList<Node>());
Node node4= new Node("safia","555",new ArrayList<Node>());
Node node5= new Node("ahmad","000",new ArrayList<Node>());
node1.getChildren().add(node2);
node2.getChildren().add(node3);
node3.getChildren().add(node4);
node4.getChildren().add(node5);
ObjectContainer db= Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(),"db");
db.store(node1);
Node node= new Node("root",null,null);
List<Node> result= db.queryByExample(node);
node= result.get(0);
System.out.println(node.getName()
+","+node.getChildren().get(0).getName()
+","+node.getChildren().get(0).getChildren().get(0).getName()
+","+node.getChildren().get(0).getChildren().get(0).getChildren().get(0).getName());
我在最后一行代码中得到一个例外,说明如下:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
答案 0 :(得分:0)
因为它对我有用,我向你展示了一个完整的工作示例:
import java.util.*;
class Node
{
String _name;
public String getName() {return _name;}
public void setName(final String name) { _name = name;}
String _value;
public String getValue() {return _value;}
public void setValue(final String value) { _value = value;}
List<Node> _children;
public List<Node> getChildren() {return _children;}
public void setChildren(final List<Node> children) { _children = children;}
Node(final String name, final String value, final List<Node> children)
{
setName(name);
setValue(value);
setChildren(children);
}
}
然后定义主类:
import java.util.*;
import com.db4o.*;
import com.db4o.query.*;
import com.db4o.ta.Activatable;
class test
{
public static void main(String[] argv)
{
Node node1= new Node("root","this is the root",new ArrayList<Node>());
Node node2= new Node("zaid","123",new ArrayList<Node>());
Node node3= new Node("saad","999",new ArrayList<Node>());
Node node4= new Node("safia","555",new ArrayList<Node>());
Node node5= new Node("ahmad","000",new ArrayList<Node>());
node1.getChildren().add(node2);
node2.getChildren().add(node3);
node3.getChildren().add(node4);
node4.getChildren().add(node5);
ObjectContainer db= Db4oEmbedded.openFile(Db4oEmbedded.newConfiguration(),"db");
db.store(node1);
Node node= new Node("root",null,null);
List<Node> result= db.queryByExample(node);
node= result.get(0);
System.out.println(
node.getName()
+","+node.getChildren().get(0).getName()
+","+node.getChildren().get(0).getChildren().get(0).getName()
+","+node.getChildren().get(0).getChildren().get(0).getChildren().get(0).getName());
}
}
并且构建/运行可以这样完成:
javac -classpath "db4o-8.0.249.16098-all-java5.jar:." *.java
java -classpath "db4o-8.0.249.16098-all-java5.jar:." test
您可以获得有关db4o的更多信息 - &gt;文档 - &gt;教程8.0。虽然8.1已发布,但没有特别的教程。