Hibernate4之一对多双自身向关联

商品分类信息可以有很多分类信息,每个分类信息都有下级关系和上级关系,所以是一对多双向自身关联.而且当一个有下级关系的对象删除后,其下级对象都会删除。
在双向自身关联中@ManyToOne默认是非延迟加载的,所以不用配置fetch属性。
而@OneToMany默认是延迟加载的,所以需要配置fetch属性。

/**
 * @author Chou
 * @since 2012-8-8
 * ...商品分类信息实体(一对多双向自身关联)
 * 
 */

@Entity
@Table(name = "TAB_GOODSCATE")
@SequenceGenerator(name = "seq", sequenceName = "SEQ_GOODSCATE", allocationSize = 1)
public class Goodscate {
	private Long id;
	private String cateNo;
	private String cateName;
	private Goodscate parent;
	private Set<Goodscate> children = new HashSet<Goodscate>();
	
	@Id
	@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
	public Long getId() {
		return id;
	}
	
	......

	@ManyToOne
	@JoinColumn(name = "PARENTID")
	public Goodscate getParent() {
		return parent;
	}

	public void setParent(Goodscate parent) {
		this.parent = parent;
	}
	
	@OneToMany(mappedBy = "parent", fetch = FetchType.EAGER,cascade = CascadeType.REMOVE)
	public Set<Goodscate> getChildren() {
		return children;
	}

	public void setChildren(Set<Goodscate> children) {
		this.children = children;
	}

}

你可能感兴趣的:(Hibernate,jpa,一对多双向自身关联)