我有兩個實體:Question和FavoritesCounter。 FavoritesCounter應該在第一次將問題添加到收藏夾時創建。如何正確處理EntityExistsException?
考慮一個用例,當兩個用戶試圖同時添加一個問題到收藏夾 - 當第二個用戶調用entityManager.persist(counter)
時,這將導致EntityExistsException
。
但低於代碼不起作用,因爲當EntityExistsException
被拋出時,容器標記事務的回滾僅並試圖返回getFavoritesCounter(question)
失敗javax.resource.ResourceException: Transaction is not active
問題
@Entity
public class Question implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
//getter and setter for id
}
Favo ritesCounter
@Entity
public class FavoritesCounter implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToOne
@Column(unique = true)
private Question question;
//getter and setter
}
什麼是EntityExistsException
後返回已經創建實體的最好方法?
謝謝,它的工作原理! – yatskevich 2010-06-15 11:55:23