Java 会话bean中的EntityManager异常处理
我有一个注入EntityManager em的托管无状态会话bean 我试图做的是创建一个具有唯一列的数据库表。然后我运行一些算法,试图插入一个实体。若实体存在,它将更新或跳过它 我想要这样的东西:Java 会话bean中的EntityManager异常处理,java,mysql,jpa,entitymanager,Java,Mysql,Jpa,Entitymanager,我有一个注入EntityManager em的托管无状态会话bean 我试图做的是创建一个具有唯一列的数据库表。然后我运行一些算法,试图插入一个实体。若实体存在,它将更新或跳过它 我想要这样的东西: try { em.persist(cd); em.flush(); } catch (PersistenceException e) { // Check if the exception is DatabaseException and ConstraintViola
try {
em.persist(cd);
em.flush();
} catch (PersistenceException e) {
// Check if the exception is DatabaseException and ConstraintViolation
// Update instead or skip it
}
问题是我只能捕获到PersistenceException
<未捕获代码>数据库异常。这是令人伤心的,因为只有DatabaseException
有一个名为getDatabaseErrorCode()
的方法,我想用来检查重复条目。我不理解它,因为PersistenceException.getCause()
返回DatabaseException
所以我的问题是:如何捕获DatabaseException
并检查MySQL错误代码
感谢您在这方面提供的任何想法和经验。我有一个建议,可以在我的应用程序中使用。我们可以从
PersistenceException
中检索SQLException
。之后,尝试获取SQLException
的sql错误代码。如果您的要求是获取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\u error\u 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
当您说您的DatabaseException未被捕获时,您的意思是您没有看到它嵌套在PersistenceException中吗?类似于:由:DatabaseException引起?我看到它嵌套在PersistenceException中。但是代码捕获(DatabaseException e)不起作用。如果DatabaseException嵌套在PersistenceException中,如何调用方法getDatabaseErrorCode()?也许这是Java的基本问题。