Hibernate Self引用相关实体

时间:2015-07-01 12:25:51

标签: hibernate annotations

我创建了一个Hibernate映射,其中Entity可以与相同类型的实体有很多关系。

@Entity
@Table
public class HelpEntity {

    public static final String MASTER_HELP = "masterHelp";
    public static final String MASTER_HELP_ID = "masterHelpId";

    private HelpEntity masterHelp;
    private List<HelpEntity> referencedHelps = new ArrayList<HelpEntity>();

    @OneToMany(mappedBy = HelpEntity.MASTER_HELP)
    public List<HelpEntity> getReferencedHelps() {
        return referencedHelps;
    }

    public void setReferencedHelps(List<HelpEntity> referencedHelps) {
        this.referencedHelps = referencedHelps;
    }

    @ManyToOne
    @JoinColumn(name = HelpEntity.MASTER_HELP_ID)
    public HelpEntity getMasterHelp() {
        return masterHelp;
    }

    public void setMasterHelp(HelpEntity masterHelp) {
        this.masterHelp = masterHelp;
    }

}

这可以像预期的那样工作,我可以创建具有其他一些&#34;相关&#34;的帮助实体。对象。

现在问题出现在删除期间...... 我差点尝试从引用中删除对象,但每次都得到

org.hibernate.ObjectDeletedException:已删除的对象将通过级联重新保存(从关联中删除已删除的对象):[xxx.HelpEntity#2]

HelpEntity#2是第一个引用的帮助...

private static boolean deleteHelp(HelpEntity entity) {

    Session session = manager.getCurrentSession();

    try {

        session.beginTransaction();

        List<HelpEntity> forDeletion = new ArrayList<HelpEntity>();
        for (HelpEntity reference : entity.getReferencedHelps()) {
            reference.setMasterHelp(null);
            forDeletion.add(reference);
        }

        entity.setReferencedHelps(null);

        for (HelpEntity reference : forDeletion) {
            session.delete(reference);
        }

        session.delete(entity);

        manager.commit(session);

        return true;

    } catch (Exception e) {
        return false;
    }

}

0 个答案:

没有答案