2015-07-10 93 views
1

我有一個MDB,它調用Singleton EJB來使用JPA維護hourlyTotals。我得到StaleObjectStateException:行被更新或者被另一個事務刪除Singleton EJB,JPA併發訪問

實體Bean代碼

@Entity 
@Table(name = "hour_db") 
public class HourlyTotalEntity { 
    @Id 
    private Date transactionTime; 

    @Column(name="success_count") 
    private long successCount; 

    @Version int version; 


    public Date getTransactionTime() { 
     return transactionTime; 
    } 

    public void setTransactionTime(Date transactionTime) { 
     this.transactionTime = transactionTime; 
    } 

    public void setSuccessCount(long successCount) 
    { 
     this.successCount = successCount; 
    } 
    public long getSuccessCount() 
    { 
     return successCount; 
    } 

    public int getVersion() { 
     return version; 
    } 

    public void setVersion(int version) { 
     this.version = version; 
    } 
} 

EJB代碼

@Singleton 
@ConcurrencyManagement(ConcurrencyManagementType.CONTAINER) 
@Lock(LockType.READ) 
public class HourlyTotalEJB { 
    @PersistenceContext (unitName="DashboardJPA") 
    private EntityManager em; 

    public void create(Date transactionTime) throws Exception 
    { 
     transactionTime = trim(transactionTime); 
     HourlyTotalEntity entity = em.find(HourlyTotalEntity.class, transactionTime,LockModeType.OPTIMISTIC_FORCE_INCREMENT); 
     if(entity == null) 
     { 
      entity = new HourlyTotalEntity(); 
      entity.setTransactionTime(transaction); 
      entity.setSuccessCount(0); 
     } 

     entity.setAuthSuccessCount(entity.getAuthSuccessCount() + 1); 
     em.persist(entity); 
     em.flush(); 
     em.clear(); 
    } 

    private Date trim(Date date) 
    { 
     Calendar calendar = Calendar.getInstance(); 
     calendar.setTime(date); 
     calendar.set(Calendar.MINUTE, 0); 
     calendar.set(Calendar.MILLISECOND, 0); 
     calendar.set(Calendar.SECOND, 0); 
     return calendar.getTime(); 
    } 
} 

的MDB調用上的onMessage創建(TRANSACTIONTIME)(消息消息)方法。在大量的transcation期間,create(transcationTime)方法將由MDBs同時調用,並導致StaleObjectStateException:Row被更新或被另一個事務刪除

如何解決上述問題?

回答

0

您正在使用read lock,這允許多個線程同時調用該方法。由於create方法不是隻讀的,因此應該使用寫入鎖定。

+0

這個問題解決了嗎? –