无限分级的tree

public class XTree{

    // 添加子节点

    public static void addNode(String pid,String name) {

        QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());

        // 查找父节点

        String sql = "select * from category where id=?";

        Category parent = (Category)runner.query(sql,pid,new BeanHandler(Category.class));

        

        // 创建子节点

        Category son = new Category();

        son.setId(UUID.randomUUID().toString());

        son.setName(name);

        son.setLft(parent.getLft());

        son.setRgt(parent.getLft()+1);

        

        // 更新所有比父节点的右支大的结点

        sql = "update category set lft=lft+2 where lft>=?";

        runner.update(sql,parent.getRgt());

        sql = "update category set rgt=rgt+2 where rgt>=?"

        runner.update(sql,parent.getRgt());

        

        // 添加子节点

        sql = "insert into category(id,name,lft,rgt) values(?,?,?,?)";

        Object[] params = {son.getId(),son.getName(),son.getLft(),son.getRgt()};

        runner.update(sql,params);        

    }

    

    // 找出层级关系

    public static List<Category> findAllParent(int lft,int rgt) {

        QueryRunner runner = new QueryRunner(JdbcUtils.getDataSource());

        String sql = "select * from category where lft<? and rgt>? order by lft";

        Object[] params = {lft,rgt};

        return runner.update(sql,params,new BeanListHandler(Category.class));        

    }

}

你可能感兴趣的:(tree)