Example usage for javax.persistence EntityExistsException getCause

List of usage examples for javax.persistence EntityExistsException getCause

Introduction

In this page you can find the example usage for javax.persistence EntityExistsException getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:org.easyj.orm.jpa.JPAEntityDao.java

/**
 * Persiste a entidade no banco de dados de acordo com o mapeamento do JPA
 *
 * @param t Entidade a ser persistida/*w  w w .ja v a 2s . c o m*/
 * @return T entidade persistida no banco:<br>
 * @throws EntityExistsException quando a entidade j existe no banco de dados
 * @throws PersistenceException para algum erro de inconsisncia de dados ou erro genrico de persistncia
 * @throws Exception qualquer outro erro inesperado
 */
public <T> T save(T t) throws EntityExistsException, PersistenceException, Exception {
    T newT = null;
    if (t != null) {
        try {
            logger.debug("Saving entity: {} [{}]", t.getClass().getSimpleName(), t.toString());
            newT = merge(t);
            logger.debug("Entity saved successfully: {} [{}]", t.getClass().getSimpleName(), newT);
        } catch (EntityExistsException e) {
            logger.error("Error saving entity: Entity already exists");
            throw e;
        } catch (PersistenceException e) {
            if (e instanceof RollbackException && e.getCause().getClass() == PersistenceException.class) {
                e = (PersistenceException) e.getCause();
            }
            String msg;
            if (e.getCause() instanceof ConstraintViolationException) {
                msg = e.getCause().getCause().getMessage();
                logger.error("Error saving entity: some constraint violation occurred: [{}] - {}", t.toString(),
                        msg);
                if (msg.toLowerCase().indexOf("duplicate") > -1) {
                    throw new EntityExistsException(msg);
                } else {
                    throw (ConstraintViolationException) e.getCause();
                }
            } else if (e.getCause() instanceof DataException) {
                logger.error("Error saving entity: inconsistent data", e);
            } else if (e.getCause() instanceof PropertyValueException) {
                logger.error("Error saving entity: missing mandatory (NOT NULL) values", e);
            } else {
                logger.error("Error saving entity: generic persistence error", e);
            }
            throw e;
        } catch (Exception e) {
            logger.error("Error saving entity: UNEXPECTED ERROR", e);
            throw e;
        }
    }
    return newT;
}