Created
October 28, 2015 09:31
-
-
Save corrspt/7351130d7878ccedab2a to your computer and use it in GitHub Desktop.
Find a duplicated row
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public T save(T e) { | |
| try { | |
| preSave(e); | |
| e.save(); | |
| return e; | |
| } catch (PersistenceException ex) { | |
| logger.debug("Error while saving instance %s with id %s", e.getClass().getName() , e.getId()); | |
| boolean isDuplicate = false; | |
| Throwable root = ex.getCause(); | |
| if (root instanceof PSQLException) { | |
| PSQLException pgException = (PSQLException) root; | |
| if ("23505".equalsIgnoreCase(pgException | |
| .getServerErrorMessage().getSQLState())) { | |
| //Must load the previous result and activate it | |
| ExpressionList<T> query = finder.where() | |
| .eq("client", owner) | |
| .eq("deleted", true); | |
| Field[] fields = e.getClass().getDeclaredFields(); | |
| for (Field f : fields){ | |
| if (f.getName().toLowerCase().contains("ebean")){ | |
| continue; | |
| } | |
| boolean isAcessible = f.isAccessible(); | |
| try { | |
| f.setAccessible(true); | |
| query.eq(f.getName(), f.get(e)); | |
| } catch (IllegalArgumentException | IllegalAccessException e1) { | |
| e1.printStackTrace(); | |
| } finally { | |
| f.setAccessible(isAcessible); | |
| } | |
| } | |
| T duplicated = query.query().findUnique(); | |
| if (duplicated != null){ | |
| duplicated.setDeleted(false); | |
| duplicated.setDeletedBy(null); | |
| duplicated.setDeletedOn(null); | |
| duplicated.save(); | |
| } else { | |
| isDuplicate = true; | |
| } | |
| } | |
| } | |
| if (isDuplicate) { | |
| throw new DuplicateKeyException(); | |
| } else { | |
| throw ex; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment