Handling EntityManager Exceptions in a Bean Session

I have a non-bean managed session with an injected EntityManager em.

What I'm trying to do is have a database table with a unique column. Then I run some algorithm that tries to insert an object. If an entity exists, 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 } 

The problem is that I can only catch a PersistenceException . DatabaseException not caught. This is sad because only DatabaseException has a method called getDatabaseErrorCode() , which I would like to use to check for duplicate records. I do not understand this because PersistenceException.getCause() returns a DatabaseException .

So my question is: how to catch DatabaseException and check MySQL error code?

Thank you for any ideas and experience.

+4
source share
1 answer

I have a suggestion that I use in my application. We can get a SQLException from a PersistenceException . After that, try to get sql error code for SQLException . If you need to get sql error code , you can follow my example;

 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 error code configuration example

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 
+6
source

Source: https://habr.com/ru/post/1442317/


All Articles