hibernate EventListener和stackoverflow错误

时间:2013-10-28 16:15:00

标签: java hibernate

我最近遇到过一种情况,当通过Hibernate会话删除对象时,我必须做一些操作。

我不想在删除实体之前删除unidirectionl relashonship,但以下代码会导致stackoverflow异常。

@Component("emsPreListener")
public class IntegrationEntityDeleteListener implements PreDeleteEventListener {

    private static final long serialVersionUID = 2245534615822054792L;

    @Override
    @SuppressWarnings("unchecked")
    public boolean onPreDelete(PreDeleteEvent event) {

        System.out.println("PRE-DELETE");

        Session session = event.getSession();

        if (event.getEntity() instanceof Project) {
            Transaction transaction = null;
            try
            {
                transaction = session.beginTransaction();

                Project project = (Project) event.getEntity();

                Criteria criteria = session.createCriteria(ProjectPoll.class);
                criteria.add(Restrictions.eq("project", project));
                List<ProjectPoll> polls = criteria.list();
                if(polls != null) {
                    for(ProjectPoll projectPoll : polls) {
                        session.delete(projectPoll);
                    }

                    return false;
                }
            }
            catch (Exception exception) {
                exception.printStackTrace();
            }
            finally
            {
                if(transaction != null) transaction.commit();
            }

        }

        return false;
    }

}

这是唯一具有重新关系的实体。

@Entity
@Table(name = "project_poll")
@PrimaryKeyJoinColumn(name = "poll_id", referencedColumnName = "id")
public class ProjectPoll extends Poll {
    private static final long serialVersionUID = -2230614967405436988L;

    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name = "project_id")
    private Project project;

    public Project getProject() {
        return project;
    }

    public void setProject(Project project) {
        this.project = project;
    }
}

TNX

1 个答案:

答案 0 :(得分:0)

您使用cascade = CascadeType.ALL注释了双向关系ProjectPoll.project。删除projectPoll也会删除父项(项目)。这反过来将再次触发onPreDelete()。尝试删除双向关系中的级联属性。