自关联测试案例
1、创建表
drop table if exists t_category ;
create table t_category (
id int(5) primary key ,
name varchar(150) ,
position int(2) ,
parent_id int(5) ,
foreign key ( parent_id ) references t_category ( id )
);
insert into t_category ( id , name , position , parent_id ) values ( 1001 , '图书音像' , 2 , null ) ;
insert into t_category ( id , name , position , parent_id ) values ( 1002 , '小说' , 2 , 1001 ) ;
insert into t_category ( id , name , position , parent_id ) values ( 1003 , '教学辅导' , 1 , 1001 ) ;
insert into t_category ( id , name , position , parent_id ) values ( 1004 , '计算机' , 3 , 1001 ) ;
insert into t_category ( id , name , position , parent_id ) values ( 1005 , '玄幻' , 2 , 1002 ) ;
insert into t_category ( id , name , position , parent_id ) values ( 1006 , '言情' , 1 , 1002 ) ;
insert into t_category ( id , name , position , parent_id ) values ( 1007 , '武侠' , 3 , 1002 ) ;
insert into t_category ( id , name , position , parent_id ) values ( 2001 , '数码产品' , 1 , null ) ;
insert into t_category ( id , name , position , parent_id ) values ( 2002 , '手机' , 1 , 2001 ) ;
insert into t_category ( id , name , position , parent_id ) values ( 2003 , '电脑' , 2 , 2001 ) ;
insert into t_category ( id , name , position , parent_id ) values ( 2004 , '相机' , 3 , 2001 ) ;
insert into t_category ( id , name , position , parent_id ) values ( 2005 , '魅族' , 2 , 2002 ) ;
insert into t_category ( id , name , position , parent_id ) values ( 2006 , '小米' , 1 , 2002 ) ;
insert into t_category ( id , name , position , parent_id ) values ( 2007 , '坚果Pro' , 3 , 2002 ) ;
分类中有一个外键parent_id 来指定父分类,并通过position来指定分类的位置。
2、持久化类
package ecut.self.entity;
import java.io.Serializable;
import java.util.List;
public class Category implements Serializable {
private static final long serialVersionUID = 4807135047518624567L;
/** 对象标识符属性 ( 属性值就是 对象标识符 ( Object Identifier ) )*/
private Integer id ;
/** 分类的名称 */
private String name ;
/** 将来在 界面 中显示时的位置*/
private int position ;
/** 先 把 当前的分类 对象 当作 一个 父分类来对待 ,那么它可能对应 多个 子分类 */
private List<Category> categories ; // 维护 从 父分类( one ) 到 子分类 ( many ) 的 一对多 关联关系
/** 再 把 当前分类对象 当作一个 子分类来对待,那么它可能有一个 父分类 */
private Category parent ; // 维护 从 子分类 ( many ) 到 父分类( one ) 的 多对一 关联关系
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public List<Category> getCategories() {
return categories;
}
public void setCategories(List&l