0

我有一个情况,多个线程加载相同的实体Job,然后每个线程都添加到它的子集合中Set<JobError>。如果父项本身已更新,我可以理解此异常,但是对父项的唯一“更改”是添加到集合中,即使这样?

父实体:

@Entity
@Table(name = "JOB")
public class Job extends BaseEntity {

private Set<JobError> jobErrors = new HashSet<JobError>();


/**
 * @return the jobErrors
 */
@OneToMany(mappedBy = "job", cascade = { CascadeType.PERSIST,
        CascadeType.MERGE, CascadeType.REMOVE })
public Set<JobError> getJobErrors() {
    return jobErrors;
}

/**
 * @param jobErrors
 *            the jobErrors to set
 */
public void setJobErrors(Set<JobError> jobErrors) {
    this.jobErrors = jobErrors;
}

/**
 * Helper to take care of both sides of the association
 * @param message
 * @param currentProfileId
 */
public void addError(String message, Long currentProfileId,
        String firstName, String lastName) {
    JobError er = new JobError(message, currentProfileId, firstName,
            lastName, this);
    jobErrors.add(er);
}
}

子实体:

@Entity
@Table(name = "JOB_ERROR")
public class JobError extends BaseEntity {
private Job job;

    public JobError(String description, Long profileId, String firstName,
        String lastName, Job job) {
    this.description = description;
    this.profileId = profileId;
    this.firstName = firstName;
    this.lastName = lastName;
    this.job = job;
}
/**
 * 
 */
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "JOB_ID", nullable = false)
public Job getJob() {
    return job;
}

/**
 * @param jobErrors
 *            the jobErrors to set
 */
public void setJob(Job job) {
    this.job = job;
}
}

服务代码,这在多个并发线程中运行:

job = jobDao.findById(er.getJobId(), false);

for (Long profileId : er.getProfileIds()) {
// do stuff
try {
    sendEmail(emailTemplateDto, user);
} catch (RuntimeException re) {
    job.addError(re.getLocalizedMessage(), currentProfileId, profile.getPersonalData().getFirstName(), profile.getPersonalData().getLastName());
}

一旦服务方法返回被注释为@Transactional(propagation = Propagation.REQUIRED)StaleObjectStateException 被抛出:

2013-03-28 13:22:52,578 ERROR     org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(324):  - Could not synchronize database state with session
org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect): [com.test.project.domain.Job#2]
at org.hibernate.persister.entity.AbstractEntityPersister.check(AbstractEntityPersister.java:1950)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2594)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2494)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2821)
at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:113)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:265)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:185)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:76)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:467)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:754)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:723)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:393)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:120)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy162.processSendEmail(Unknown Source)
at com.test.project.service.messaging.EmailRequestMessageListener.onMessage(EmailRequestMessageListener.java:57)
at org.springframework.jms.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:560)
at org.springframework.jms.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:498)
at org.springframework.jms.listener.AbstractMessageListenerContainer.doExecuteListener(AbstractMessageListenerContainer.java:467)
at org.springframework.jms.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:439)
at org.springframework.jms.listener.SimpleMessageListenerContainer.processMessage(SimpleMessageListenerContainer.java:311)
at org.springframework.jms.listener.SimpleMessageListenerContainer$2.onMessage(SimpleMessageListenerContainer.java:287)
at org.apache.activemq.ActiveMQMessageConsumer.dispatch(ActiveMQMessageConsumer.java:1321)
at org.apache.activemq.ActiveMQSessionExecutor.dispatch(ActiveMQSessionExecutor.java:131)
at org.apache.activemq.ActiveMQSessionExecutor.iterate(ActiveMQSessionExecutor.java:202)
at org.apache.activemq.thread.PooledTaskRunner.runTask(PooledTaskRunner.java:129)
at org.apache.activemq.thread.PooledTaskRunner$1.run(PooledTaskRunner.java:47)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)

除了尝试直接保存之外,我什么都想不到JobError。目前我首先加载Job,添加到集合JobError然后mergeJob 并希望 cascade.merge 将负责保存子集合。

任何指针将不胜感激。

4

1 回答 1

0

我不知道这是否是有问题的异常的原因,但如果不是,它会导致问题:HashSet 不是线程安全集合,这意味着如果两个线程同时调用 addError那么其中一个错误可能不会进入集合。您要么需要在 addError 方法中添加“synchronized”关键字,要么需要将 HashSet 替换为线程安全的替代方案,例如 ConcurrentLinkedQueue 或 ConcurrentHashMap

于 2013-03-28T20:39:09.837 回答