gpt4 book ai didi

java - 合并的 JPA 异常

转载 作者:行者123 更新时间:2023-11-30 06:05:45 24 4
gpt4 key购买 nike

为什么 JPA 不在我执行合并的方法中针对违反唯一约束的情况抛出异常?相反,我在代码的其他地方看到了抛出的异常。

我想获取异常消息,如(更新错误),但它没有捕获异常。

我想得到这样的回应:

{
"errorMessage": "Update Error",
"errorCode": 404,
"documentation": ""
}

相反,在控制台中我得到了这个错误:

Caused by: javax.ejb.EJBTransactionRolledbackException: Transaction rolled back
.....
...
Caused by: javax.transaction.RollbackException: ARJUNA016053: Could not commit transaction.
.....
.....
Caused by: javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
......
.....
Caused by: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (DEMAND_TD_CODE) violated
.....
....

这是我进行更新的地方:

@Override
public Demand updateDemand(Demand demand) throws DemandExceptions {
try {
Demand demandToUpdate = entityManager.merge(demand);
} catch (PersistenceException e) {
throw new DemandExceptions("Update Error");
}
return demandToUpdate;
}

请求异常.java

public class DemandeExceptions extends Exception implements Serializable {
private static final long serialVersionUID = 1L;
public DemandeExceptions (String message) {
super(message);
}
}

@Provider
public class DemandExceptionsMapper implements ExceptionMapper<DemandeExceptions >{

@Override
public Response toResponse(DemandeExceptions ex) {
ErrorMessage errorMessage = new ErrorMessage(ex.getMessage(), 404, "");
return Response.status(Status.NOT_FOUND)
.entity(errorMessage)
.build();
}

}

错误信息.java

@XmlRootElement
public class ErrorMessage {

private String errorMessage;
private int errorCode;
private String documentation;
..
}

最佳答案

为了提高性能,大多数 JPA 实现都会缓存数据库操作,而不是在每次 JPA 方法调用时都访问数据库。这意味着当您调用 merge() 时,更改记录在 JPA 实现正在管理的 Java 数据结构中,但数据库中尚未发生任何更新。

JPA 实现不会检测唯一约束违规等问题 - 这是留给数据库处理的。

这意味着在捕获 PersistenceException 的 try block 中不会发生唯一约束冲突。相反,当 JPA 决定它需要将该更新刷新到数据库时抛出异常。这种自动刷新通常在事务提交时发生,但也可能发生得更早(例如,如果需要对更新后的表执行查询)。

您可以通过调用 EntityManager.flush() 手动刷新 JPA 状态。如果您在 try block 中执行此操作,您将在您认为会出现的位置获得 PersistenceException。

    try {
Demand demandToUpdate = entityManager.merge(demand);
entityManager.flush();
} catch (PersistenceException e) {
throw new DemandExceptions("Update Error: " + e.getMessage());
}

关于java - 合并的 JPA 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45797554/

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