当前位置: 代码迷 >> J2EE >> 请问一个hibernate递归映射的有关问题
  详细解决方案

请问一个hibernate递归映射的有关问题

热度:314   发布时间:2016-04-22 03:35:15.0
请教一个hibernate递归映射的问题.
composite模式中如果我要以树状展示某部门 
部门下又有子部门这个在hibernate中该怎么映射 

我试着直接在域变量中加入一个变量parent 类型为自身但是映射时它报错说无法解析的类型 


我通过手工编码的方式算是解决了这个问题 但是觉得这样设计不是太科学 不知道hibernate中是否专门有方法支持这种映射  

劳烦赐教 

以下为我的解决方案
Java code
package shadowingfly; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Transient; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.cfg.Configuration; @Entity public class Department { private int id; private int pid; private Department parent;// 此属性为暂态 从数据库拿到对象后必须手工赋值(封装在存取器里) private String name; private boolean isRoot; private String description;// 备注 public Department(Department parent, String name, boolean isRoot, String description) { this.description = description; this.setParent(parent); this.name = name; this.isRoot = isRoot; } public Department() { } @Id @GeneratedValue(strategy = GenerationType.TABLE) public int getId() { return id; } public void setId(int id) { this.id = id; } @Transient // 从数据库拿到后手工赋值该属性 public Department getParent(SessionFactory sf) { if (this.parent != null || this.isRoot == true || this.isTransient()) return parent; else { Session s = sf.openSession(); Transaction tran = s.beginTransaction(); Department p = (Department) s.get(Department.class, this.getPid()); tran.commit(); s.close(); this.parent = p; return p; } } public void setParent(Department parent)// 该方法内给pid赋值 { this.parent = parent; this.setPid(parent.id); } public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isRoot() { return isRoot; } public void setRoot(boolean isRoot) { this.isRoot = isRoot; } public String getDescription() { return description; } public int getPid() { return pid; } public void setPid(int pid) { this.pid = pid; } public void setDescription(String description) { this.description = description; } @Transient public boolean isTransient() { return getId() < 1; } } 


------解决方案--------------------
看下我的这个帖子,用hibernate实现树状结构。
http://blog.csdn.net/pizzame/archive/2007/10/09/1816811.aspx
  相关解决方案