無限階層tree

3132 ワード

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));        

    }

}