我有一个类别实体,它有一个类别作为父类别,一个类别列表作为子类别。这是它的声明:
@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...
它在保存和更新时工作正常,但是当尝试获取所有类别时......每个孩子也返回一个父母!我的意思是,如果我有一个 mainCat 并且这个 mainCat 有 4 个孩子,例如,当从 db 获取所有类别时,它返回所有四个孩子和令人惊讶的 4 个 mainCat ...奇怪的部分是返回的对象是正确的,它们的属性是设置正确和 4 mainCat 是一样的!!!我该怎么办?
我使用以下代码来检索结果:
public List<E> find(E example, final PagingObject paging, Map<?, ?> filter) throws Exception {
// create the criteria
final DetachedCriteria detachedCriteria = createCriteria(filter);
// add restrictions to the criteria based on example entity
pruneCriteria(detachedCriteria, example);
List<E> result = getHibernateTemplate().execute(new HibernateCallback<List<E>>() {
@SuppressWarnings("unchecked")
@Override
public List<E> doInHibernate(Session session) throws HibernateException, SQLException {
// attach criteria to the session
Criteria criteria = detachedCriteria.getExecutableCriteria(session);
// add paging and sort to the criteria
paginate(criteria, paging);
List<E> list = criteria.list();
return list;
}
});
return result;
}