gpt4 book ai didi

java - session bean 中的 EntityManager 异常处理

转载 作者:可可西里 更新时间:2023-11-01 07:28:23 24 4
gpt4 key购买 nike

我有一个注入(inject)了 EntityManager em 的托管无状态 session bean。

我想要做的是拥有一个包含唯一列的数据库表。然后我运行一些试图插入实体的算法。但是,如果实体存在,它将更新它或跳过它。

我想要这样的东西:

try {   
em.persist(cd);
em.flush();
} catch (PersistenceException e) {
// Check if the exception is DatabaseException and ConstraintViolation
// Update instead or skip it
}

问题是我只能捕获PersistenceExceptionDatabaseException 未被捕获。令人难过的是,只有 DatabaseException 具有名为 getDatabaseErrorCode() 的方法,我想用它来检查重复条目。我不明白,因为 PersistenceException.getCause() 返回 DatabaseException

所以我的问题是:如何捕获 DatabaseException 并检查 MySQL 错误代码?

感谢您对此的任何想法和经验。

最佳答案

我在我的申请中使用了一个建议。我们可以从 PersistenceException 中检索 SQLException。之后,尝试获取 SQLExceptionsql 错误代码。如果你的需求是获取sql错误码,可以按照我的例子进行;

public void insert(Group group) throws DAOException {
try {
//your operation
em.flush();
logger.debug("insert() method has been successfully finisehd.");
} catch (PersistenceException pe) {
String sqlErroCode = getErrorCode(pe);
// do your operation based on sql errocode
}
}

protected String getErrorCode(RuntimeException e) {
Throwable throwable = e;
while (throwable != null && !(throwable instanceof SQLException)) {
throwable = throwable.getCause();
}
if (throwable instanceof SQLException) {
Properties properties = --> load sql error code form configuration file.
SQLException sqlex = (SQLException) throwable;
String errorCode = properties.getProperty(sqlex.getErrorCode() + "");
return errorCode;
}
return "NONE";
}

mysql错误码配置示例

mysql_error_code.properties

#MySQL Database
1062=DUPLICATE_KEY_FOUND
1216=CHILD_RECORD_FOUND
1217=PARENT_RECORD_NOT_FOUND
1048=NULL_VALUE_FOUND
1205=RECORD_HAS_BEEN_LOCKED

关于java - session bean 中的 EntityManager 异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13088499/

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