我最近遇到了一种情况,当通过 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;
}
}
这是唯一一个具有 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;
}
}
肿瘤坏死因子