[英]EntityManager exception handling in session bean
I have a managed stateless session bean with injected EntityManager em. 我有一个注入了EntityManager em的托管无状态会话bean。
What I am trying to do is to have a database table with unique column. 我想做的是让数据库表具有唯一列。 Then I run some algorithm which is trying to insert an entity.
然后,我运行一些尝试插入实体的算法。 If entity exists however it will update it or skip it.
如果实体存在,它将更新或跳过它。
I would like to have something like this: 我想要这样的东西:
try {
em.persist(cd);
em.flush();
} catch (PersistenceException e) {
// Check if the exception is DatabaseException and ConstraintViolation
// Update instead or skip it
}
Problem is that I am able to catch only PersistenceException
. 问题是我只能捕获
PersistenceException
。 DatabaseException
is not catched. 未捕获
DatabaseException
。 It is sad because only DatabaseException
has method called getDatabaseErrorCode()
I would like to use to check duplicate entry. 令人遗憾的是,只有
DatabaseException
具有名为getDatabaseErrorCode()
方法,我想用它来检查重复项。 I dont understand it because PersistenceException.getCause()
returns DatabaseException
. 我不明白,因为
PersistenceException.getCause()
返回DatabaseException
。
So my question is: How do I catch DatabaseException
and check the MySQL error code? 所以我的问题是:如何捕获
DatabaseException
并检查MySQL错误代码?
Thank you for any ideas and experiences with this. 感谢您的任何想法和经验。
I have a suggestion which is I use in my application. 我有一个建议,可以在我的应用程序中使用。 We can retrieve the
SQLException
from PersistenceException
. 我们可以从
PersistenceException
检索SQLException
。 After that, try to get sql error code
for SQLException
. 之后,尝试获取
SQLException
sql error code
。 If your requirement is to get the sql error code
, your can follow my example; 如果您的要求是获取
sql error code
,则可以按照我的示例进行;
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";
}
Example error code configuration of mysql mysql的错误代码示例配置
mysql_error_code.properties 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.