gpt4 book ai didi

java - 如何正确处理 EntityExistsException?

转载 作者:行者123 更新时间:2023-11-30 09:55:00 26 4
gpt4 key购买 nike

我有两个实体:Question 和 FavoritesCounter。首次将问题添加到 Collection 夹时,应创建 FavoritesCounter。

考虑一个用例,当两个用户试图同时将问题添加到 Collection 夹时 - 当为第二个用户调用 entityManager.persist(counter) 时,这将导致 EntityExistsException .

但是下面的代码不起作用,因为当抛出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

}

Collection 夹计数器

@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 之后返回已创建实体的最佳方法是什么?

最佳答案

您可以将 createCounter() 移动到另一个 session Bean 并使用 @TransactionAttribute(REQUIRES_NEW) 标记该方法

或者,您可以将 createCounter() 移动到 FavoritesServiceBean 的本地接口(interface)(同时确保添加 @TransactionAttribute(REQUIRES_NEW) 注释)并按如下方式调用它:

@Stateless
public class FavoritesServiceBean implements FavoritesService
{

...
@Resource
protected SessionContext sessionContext;

public void addToFavorites(Question question)
{
FavoritesCounter counter = getCounter(question);
if (counter == null) {
counter = sessionContext.getBusinessObject(FavoritesService.class)
.createCounter(question);
}
//increase counter
}

@TransactionAttribute(REQUIRES_NEW)
public FavoritesCounter createCounter(Question question)
{
...
}
...
}

您需要通过业务/本地接口(interface)而不是直接调用 createCounter(),以便容器知道开始新事务。

关于java - 如何正确处理 EntityExistsException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3037499/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com