NutzCN Logo
问答 自关联树形结构怎么一次插入所有记录
发布于 2852天前 作者 qq_75eaf26a 1261 次浏览 复制 上一个帖子 下一个帖子
标签:
package com.test.ioc;
import java.util.List;
import org.nutz.dao.entity.annotation.Column;
import org.nutz.dao.entity.annotation.Id;
import org.nutz.dao.entity.annotation.Many;
import org.nutz.dao.entity.annotation.One;
import org.nutz.dao.entity.annotation.Table;

@Table("t_tree")
public class Tree {
	@Id
	private long id;
	@Column
	private String name;
	@One(field="pid")
	private Tree parent;
	@Many(field="pid")
	private List<Tree> Children;
	@Column
	private long pid;
	
	public long getId() {
		return id;
	}
	public void setId(long id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Tree getParent() {
		return parent;
	}
	public void setParent(Tree parent) {
		this.parent = parent;
	}
	public List<Tree> getChildren() {
		return Children;
	}
	public void setChildren(List<Tree> children) {
		Children = children;
	}
}
package com.test.list;

import java.util.ArrayList;
import java.util.List;

import org.nutz.dao.Dao;
import org.nutz.ioc.Ioc;
import org.nutz.ioc.impl.NutIoc;
import org.nutz.ioc.loader.json.JsonLoader;

import com.test.ioc.Tree;

public class TreeTest {
	public static void main(String[] args) {
		Ioc ioc = new NutIoc(new JsonLoader("ioc/dao.js"));
		Dao dao = ioc.get(Dao.class);
		Tree tree1 = new Tree();
		Tree tree2 = new Tree();
		Tree tree3 = new Tree();
		Tree tree4 = new Tree();
		Tree tree5 = new Tree();
		Tree tree6 = new Tree();
		
		
		List<Tree> list1 = new ArrayList<Tree>();
		List<Tree> list2 = new ArrayList<Tree>();
		List<Tree> list3= new ArrayList<Tree>();
		
		tree1.setName("根节点");
		tree2.setName("子节点1");
		tree3.setName("子节点2");
		tree4.setName("孙子节点1");
		tree5.setName("孙子节点2");
		tree6.setName("孙子节点3");
		
		list1.add(tree2);
		list1.add(tree3);
		list2.add(tree4);
		list2.add(tree5);
		list3.add(tree6);
		
		tree1.setChildren(list1);
		tree2.setChildren(list2);
		tree3.setChildren(list3);
		
		tree2.setParent(tree1);
		tree3.setParent(tree1);
		tree4.setParent(tree2);
		tree5.setParent(tree2);
		tree6.setParent(tree3);
		
		dao.create(Tree.class, true);
		dao.insertWith(tree1, null);
		
	}
}

请问上面定义了一个树形结构是否正确? 下面测试的时候tree1 tree2 tree3插入进了数据库 tree4 tree5 tree6貌似没有插入数据库,怎么插入tree1的时候能把所有的子节点孙子节点全部插入进去呢?另外好像不写 tree2.setParent(tree1)这些也可以,那查询的时候能把所有的子节点孙节点一次查询出来吗?

1 回复

只能递归一下了

添加回复
请先登陆
回到顶部