当前位置:编程学习 > JSP >>

Hibernate高效处理Tree型数据

  1. import java.util.ArrayList;   
  2. import java.util.List;   
  3. import javax.persistence.Entity;   
  4. import javax.persistence.FetchType;   
  5. import javax.persistence.Id;   
  6. import javax.persistence.JoinColumn;   
  7. import javax.persistence.ManyToOne;   
  8. import javax.persistence.Transient;   
  9. import org.hibernate.annotations.Cache;   
  10. import org.hibernate.annotations.CacheConcurrencyStrategy;   
  11. @Entity  
  12. @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)   
  13. public class MerType {   
  14.  private int id;   
  15.     
  16.  private String name;   
  17.     
  18.  private MerType parent;   
  19.     
  20.  private List<MerType> children;   
  21.     
  22.  public void addChild(MerType c){   
  23.   if(children == null){   
  24.    children = new ArrayList<MerType>();   
  25.   }   
  26.   children.add(c);   
  27.  }   
  28.     
  29.  @Id  
  30.  public int getId() {   
  31.   return id;   
  32.  }   
  33.  public void setId(int id) {   
  34.   this.id = id;   
  35.  }   
  36.  public String getName() {   
  37.   return name;   
  38.  }   
  39.  public void setName(String name) {   
  40.   this.name = name;   
  41.  }   
  42.     
  43.  @ManyToOne(fetch=FetchType.EAGER, targetEntity=MerType.class)   
  44.  @JoinColumn(name="P_ID")   
  45.  public MerType getParent() {   
  46.   return parent;   
  47.  }   
  48.  public void setParent(MerType parent) {   
  49.   this.parent = parent;   
  50.   //设置父节点的时候,将当前节点加入到父节点的孩子列表中   
  51.   if(parent != null){   
  52.     parent.addChild(this);   
  53.   }   
  54.  }   
  55.  @Transient  
  56.  public List<MerType> getChildren() {   
  57.   return children;   
  58.  }   
  59.     
  60.  public void setChildren(List<MerType> children) {   
  61.   this.children = children;   
  62.  }   
  63. }  


数据库脚本
CREATE TABLE MERTYPE (
ID int(11) NOT NULL PRIMARY KEY,
NAME varchar(20) NOT NULL,
P_ID int(11) default NULL)

测试代码:

Java代码 复制代码
  1. SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();   
  2. Session session = sessionFactory.openSession();   
  3.   
  4. //一次取出全部节点   
  5. Query query = session.createQuery("from MerType as m");   
  6. List<MerType> list = query.list();   
  7. //从一级缓存中取出根节点(根节点为1000)   
  8. MerType root = (MerType) session.get(MerType.class1000);   
  9.   
  10. session.close();   
  11. sessionFactory.close();  
补充:Jsp教程,Java基础 
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,