日期:2014-05-20 浏览次数:20697 次
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; } }