Monday, May 14, 2012

how to annotate an entity with a list of itself in it using Hibernate Annotation

I have a category entity that has a category as parent and a list of category as child. here's it's declaration:



@Entity
@Table(name="CATEGORYENTITY")
public class CategoryEntity extends BaseEntity<Long> {
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
@Column(name="ID")
private Long id;

@Column(name="NAME")
private String name;

@Column(name="VIEWSCOUNT")
private Integer viewsCount;

@OneToMany(fetch=FetchType.EAGER, cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
@Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
@JoinColumn(name="CATEGORY_ID")
private List<CategoryEntity> childCategories;

@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="CATEGORY_ID")
private CategoryEntity parent;

setters and getters...


It works fine when saving and updating but when try to get all of the categories... for each child returns a parent too!!! I mean if i have a mainCat and this mainCat has 4 child for example, when getting all categories from db, it returns all of the four child and surprisingly 4 mainCat... the weird part is that returned objects are correct and their properties are set correct and 4 mainCat are same!!! what should I do?





No comments:

Post a Comment