我有两个实体:Question 和 FavoritesCounter。首次将问题添加到收藏夹时,应创建 FavoritesCounter。
考虑两个用户同时尝试将问题添加到收藏夹的用例 - 这将导致EntityExistsException
调用entityManager.persist(counter)
第二个用户的时间。
但是下面的代码不起作用,因为当EntityExistsException
被抛出时,容器将事务标记为仅回滚并尝试返回getFavoritesCounter(question)
失败javax.resource.ResourceException: Transaction is not active
@Stateless
public class FavoritesServiceBean implements FavoritesService {
...
public void addToFavorites(Question question) {
FavoritesCounter counter = getCounter(question);
if (counter == null) {
counter = createCounter(question);
}
//increase counter
}
private FavoritesCounter createCounter(Question question) {
try {
FavoritesCounter counter = new FavoritesCounter();
counter.setQuestion(question);
entityManager.persist(counter);
entityManager.flush();
return counter;
} catch (EntityExistsException e) {
return getFavoritesCounter(question);
}
}
private FavoritesCounter getFavoritesCounter(Question question) {
Query counterQuery = entityManager.createQery("SELECT counter FROM FavoritesCounter counter WHERE counter.question = :question");
counterQuery.setParameter("question", question);
List<FavoritesCounter> result = counterQuery.getResultList();
if (result.isEmpty()) return null;
return result.get(0);
}
}
问题
@Entity
public class Question implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
//getter and setter for id
}
收藏计数器
@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
?