一对多映射
创建一个图书分类,图书下面有子分类
主分类创建
public class Item {
private int iid;
private String title;
private SubItem[] subItems;
public Item(int iid, String title) {
this.iid = iid;
this.title = title;
}
getter and setter 方法略
需返回的信息:
public String getinfo(){
return "【分类】 id:" +this.iid+", 书名:"+this.title;
}
创建子分类
public class SubItem {
private int sid;
private String title;
private Item item;
public SubItem(int sid, String title) {
this.sid = sid;
this.title = title;
}
getter and setter 方法略
public String getinfo(){
return "【子分类】 id:"+this.sid+"书名:"+this.title;
}
主方法
public class ItemDemo {
public static void main(String[] args) {
Item item = new Item(1,"计算机编程");
// Item item1 = new Item(2,"其他");
SubItem[] subItems = new SubItem[]{
new SubItem(1,"java"),
new SubItem(2,"python"),
new SubItem(3,"C++")
};
将二者联系
item.setSubItems(subItems);
for (SubItem subItem : subItems) {
subItem.setItem(item);
}
获取信息
System.out.println(item.getinfo());
for (int i = 0; i < item.getSubItems().length; i++) {
System.out.println("\t|--"+item.getSubItems()[i].getinfo());
}
结果
【分类】 id:1, 书名:计算机编程
|--【子分类】 id:1书名:java
|--【子分类】 id:2书名:python
|--【子分类】 id:3书名:C++