简体   繁体   中英

hibernate EventListener and stackoverflow error

I recently came across a situation where I have to do some actions when object is deleted through Hibernate session.

I wan't to remove unidirectionl relashonship before an entity is deleted, but the following code results in a stackoverflow exception.

@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;
    }

}

This it the only entity with the relashonship.

@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

You annotated bidirectional relation ProjectPoll.project with cascade=CascadeType.ALL. Removing a projectPoll will remove also a parent (project). This in turn will trigger onPreDelete() once more. Try to remove cascade attribute on bidirectional relation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM