将以上的结构转换为类结构,并且可以获取如下的信息:
获取一个用户访问的所有商品的详细信息;
获取一个商品被浏览过的全部的用户信息;
对于此时的程序只需要去考虑实体表的设计即可,也就是说对于中间的访问记录信息表不要求你进行转换处理,之定义两个类即可。
范例:
class Member{
private String mid;
private String name;
private Product products []; //多个商品
public Member(String mid,String name){
this.mid = mid;
this.name = name;
}
public void setProducts(Product products[]){
this.products = products;
}
public Product[] getProducts(){
return this.products;
}
// setter、getter、无参构造略
public String getInfo(){
return "【用户信息】mid = " + this.mid + "、name = " + this.name;
}
}
class Product{
private long pid;
private String name;
private double price;
private Member members[];
public Product(long pid,String name,double price){
this.pid = pid;
this.name = name;
this.price = price;
}
// setter、getter、无参构造略
public void setMembers(Member members[]){
this.members = members;
}
public Member[] getMembers(){
return this.members;
}
public String getInfo(){
return "【商品信息】pid =" + this.pid + "、name = " + this.name + "、price = " + this.price;
}
}
public class JavaDemo{
public static void main(String args[]){
//第一步:根据结构设置对象数据
Member memA = new Member("mldn","李四");
Member memB = new Member("mldn","张三");
Product proA = new Product(1L,"Java开发图书",79.8);
Product proB = new Product(2L,"很高端大气的耳机",2399.0);
Product proC = new Product(3L,"小米手机10",3999.0);
memA.setProducts(new Product[]{proA,proB,proC});
memB.setProducts(new Product[]{proA});
proA.setMembers(new Member[]{memA,memB});
proB.setMembers(new Member[]{memA});
proC.setMembers(new Member[]{memA});
//第二步:根据要求获取数据
System.out.println("--------------根据用户查看浏览商品信息---------------");
System.out.println(memA.getInfo());
for(int x = 0;x<memA.getProducts().length; x++){
System.out.println("\t|- " + memA.getProducts()[x].getInfo());
}
System.out.println("--------------查看商品被浏览的记录---------------");
System.out.println(proA.getInfo());
for(int x = 0; x < proA.getMembers().length; x++){
System.out.println("\t|- " + proA.getMembers()[x].getInfo());
}
}
}