a:首先先看下一个简单的面试题
斐波那契数列
计算数组{1,1,2,3,5,8.......} 第30位值
规律:1 1 从第三项开始,每一项都是前两项之和
有两种实现方式
第一种方式:
testself((n<0 illegalargumentexception("n不能为负数" (n<=2 1 testself(n-2)+testself(n-1 30
第二种方式:利用数组
public int testselftwo(int n){ if(n<0){ throw new illegalargumentexception("n不能为负数");
}else if(n<=1){ //递归前两个数 不管n是多少 为一 return 1;
} int[] nums = new int[n+1]; //30位从零开始 nums[0]=1;
nums[1]=1; for (int i =2;i<n;i++){
nums[i] = nums[i-2]+nums[i-1];
} return nums[n-1];
}
@test public void test(){
system.out.println(testselftwo(30));
}
公式:f(n) = f(n-2)+f(n-1) f代表方法 n代表多少 位
b:在mybatis中利用递归实现n级联动
sql语句:select * from type where pid = 0; 首次指定pid值为0,然后下次根据pid为0的cid 作为下次查询的pid
public list<category> getcategory(integer pid); //接口层方法
映射文件配置<mapper namespace="dao.categorydao"><resultmap id="getself" type="entity.category"><id column="cid" property="cid"></id><result column="cname" property="cname"></result><collection property="categoryset" select="getcategory" column="cid"></collection> //这里可以不用指定oftype 使用反向查询select从另一个maper文件中取出数据时必须用oftype<!--查到的cid作为下次的pid--></resultmap><select id="getcategory" resultmap="getself" >select * from category where pid=#{pid}</select></mapper>
mybatis的javatype和oftype
都是指定对象的类型 不同的是当使用反向查询select从另一个maper文件中取出数据时必须用oftype
都可以为collection和association是指定对象的类型,
都不是必须写的, 只有反向select时需要oftype;
实体类:
package entity;import java.util.hashset;import java.util.set;/**
* created by zhangyu on 2017/7/12. */public class category {private integer cid;private string cname;private integer pid;private set<category> categoryset = new hashset<category>();
@overridepublic string tostring() {return category{ +
cid= + cid +
, cname=' + cname + '\'' +
, pid= + pid +
, categoryset= + categoryset +
'}';
}public integer getcid() {return cid;
}public void setcid(integer cid) {this.cid = cid;
}public string getcname() {return cname;
}public void setcname(string cname) {this.cname = cname;
}public integer getpid() {return pid;
}public void setpid(integer pid) {this.pid = pid;
}public set<category> getcategoryset() {return categoryset;
}public void setcategoryset(set<category> categoryset) {this.categoryset = categoryset;
}
}
测试类:
//测试自连接 @testpublic void testself(){
categorydao dao = mybatis.getsessiontwo().getmapper(categorydao.class);
list<category> list = dao.getcategory(0);for (category item:list ) {
system.out.println(item);
}
}
打印结果:
category{cid=1, cname='图书', pid=0, categoryset=[category{cid=5, cname='期刊报纸', pid=1, categoryset=[]}, category{cid=3, cname='青年图书', pid=1, categoryset=[category{cid=6, cname='读者', pid=3, categoryset=[category{cid=7, cname='12月份', pid=6, categoryset=[]}]}]}, category{cid=4, cname='少儿图书', pid=1, categoryset=[]}]}
category{cid=2, cname='服装', pid=0, categoryset=[]}
以上就是mybatis自查询并使用递归实现 n级联动的详细内容。