Example usage for org.hibernate.exception ConstraintViolationException getErrorCode

List of usage examples for org.hibernate.exception ConstraintViolationException getErrorCode

Introduction

In this page you can find the example usage for org.hibernate.exception ConstraintViolationException getErrorCode.

Prototype

public int getErrorCode() 

Source Link

Document

Get the vendor specific error code from the underlying SQLException .

Usage

From source file:de.phoenix.webresource.util.AbstractPhoenixResource.java

License:Open Source License

private boolean isDuplicateEntryError(ConstraintViolationException e) {
    return e.getErrorCode() == DUPLICATE_SQL_ERROR && e.getSQLState().equals(DUPLICATE_SQL_STATE);
}

From source file:es.logongas.ix3.dao.impl.ExceptionTranslator.java

License:Apache License

public List<BusinessMessage> getBusinessMessages(org.hibernate.exception.ConstraintViolationException cve) {
    List<BusinessMessage> businessMessages = new ArrayList<BusinessMessage>();
    BusinessMessage businessMessage;/*from   w  ww.j  a v a2 s .  co  m*/

    String message;
    int errorCode;
    String sqlState;

    if (cve.getSQLException() != null) {
        message = cve.getSQLException().getLocalizedMessage();
        errorCode = cve.getSQLException().getErrorCode();
        sqlState = cve.getSQLException().getSQLState();
    } else {
        message = cve.getLocalizedMessage();
        errorCode = cve.getErrorCode();
        sqlState = cve.getSQLState();
    }

    es.logongas.ix3.core.database.ConstraintViolation constraintViolation = constraintViolationTranslator
            .translate(message, errorCode, sqlState);

    if (constraintViolation == null) {
        throw cve;
    } else {
        businessMessage = new BusinessMessage(constraintViolation.getMessage());
    }

    businessMessages.add(businessMessage);

    return businessMessages;
}

From source file:motor.MOTOR.java

/**
 * Mtodo que elimina registros de una base de datos. Elimina un cliente
 * buscandolo por su identificador de coche.Utiliza operaciones elementales
 *
 * @param clienteId: el identificador del cliente a eliminar
 * @throws ExceptionMotor excepcion que integra el mensaje de error al
 * usuario, el codigo de error y el mensaje de error que nos ha devuelto la
 * base de datos/* www. ja va 2s.  co  m*/
 */
public void eliminarClientes(BigDecimal clienteId) throws ExceptionMotor {
    Transaction t = sesion.beginTransaction();

    //Se crea un objeto Cliente transitorio
    Cliente cliente = new Cliente(clienteId, "", "", "", "", "");

    try {

        sesion.delete(cliente);
        // Se confirma la transaccin
        t.commit();

    } catch (StaleStateException ssEx) {
        ExceptionMotor ex = new ExceptionMotor();

        ex.setMensajeErrorUsuario("Error. El identificador de cliente no existe");
        ex.setMensajeErrorAdministrador(ssEx.getMessage());

        throw ex;
    } catch (ConstraintViolationException igEx) {
        ExceptionMotor ex = new ExceptionMotor();

        ex.setCodigoErrorAdministrador(igEx.getErrorCode());
        ex.setSentenciaSQL(igEx.getSQL());
        ex.setMensajeErrorUsuario("Error. Hay coches asociados a este cliente");
        ex.setMensajeErrorAdministrador(igEx.getMessage());

        throw ex;
    } catch (Exception e) {
        ExceptionMotor ex = new ExceptionMotor();

        ex.setCodigoErrorAdministrador(0);
        ex.setMensajeErrorUsuario("Error general en el sistema, Consulte con el administrador");
        ex.setMensajeErrorAdministrador(e.getMessage());

        throw ex;
    }

}

From source file:motor.MOTOR.java

/**
 * Mtodo que modifica los registros de un cliente ya existente. Utiliza
 * operaciones elementales/*w  w  w .ja va  2s  .  co m*/
 *
 * @param cliente los datos del coche a modificar
 * @throws ExceptionMotor excepcion que integra el mensaje de error al
 * usuario, el codigo de error y el mensaje de error que nos ha devuelto la
 * base de datos
 */
public void modificarCliente(Cliente cliente) throws ExceptionMotor {
    Transaction t = sesion.beginTransaction();

    try {

        sesion.update(cliente);
        // Se confirma la transaccin
        t.commit();

    } catch (ConstraintViolationException cvEx) {
        ExceptionMotor ex = new ExceptionMotor();

        if (cvEx.getErrorCode() == 2290) {
            ex.setCodigoErrorAdministrador(cvEx.getErrorCode());
            ex.setSentenciaSQL(cvEx.getSQL());
            ex.setMensajeErrorUsuario(
                    "Error. El campo telefono debe empezar por 6 o 9 y contener 9 caracteres numricos y el email debe acabar en .com o .es");
            ex.setMensajeErrorAdministrador(cvEx.getMessage());

        } else {
            ex.setCodigoErrorAdministrador(cvEx.getErrorCode());
            ex.setSentenciaSQL(cvEx.getSQL());
            ex.setMensajeErrorUsuario("Error. Los siguientes campos son unicos: dni, email y telefono");
            ex.setMensajeErrorAdministrador(cvEx.getMessage());
        }
        throw ex;
    } catch (PropertyValueException pvEx) {
        ExceptionMotor ex = new ExceptionMotor();

        ex.setMensajeErrorUsuario(
                "Error. Los siguientes campos son obligatorios: nombre, apellido1, email, telefono, dni");
        ex.setMensajeErrorAdministrador(pvEx.getMessage());

        throw ex;
    } catch (SQLGrammarException sqlEx) {
        ExceptionMotor ex = new ExceptionMotor();

        ex.setCodigoErrorAdministrador(sqlEx.getErrorCode());
        ex.setSentenciaSQL(sqlEx.getSQL());
        ex.setMensajeErrorUsuario("Error. El telefono es un campo numerico");
        ex.setMensajeErrorAdministrador(sqlEx.getMessage());

        throw ex;
    } catch (GenericJDBCException jdbcEx) {
        ExceptionMotor ex = new ExceptionMotor();

        if (jdbcEx.getErrorCode() == 20004) {
            ex.setCodigoErrorAdministrador(jdbcEx.getErrorCode());
            ex.setSentenciaSQL(jdbcEx.getSQL());
            ex.setMensajeErrorUsuario("Error. El taller esta cerrado");
            ex.setMensajeErrorAdministrador(jdbcEx.getMessage());
        }
        if (jdbcEx.getErrorCode() == 20005) {
            ex.setCodigoErrorAdministrador(jdbcEx.getErrorCode());
            ex.setSentenciaSQL(jdbcEx.getSQL());
            ex.setMensajeErrorUsuario("Error. El email debe acabar por .com o .es");
            ex.setMensajeErrorAdministrador(jdbcEx.getMessage());
        }
        if (jdbcEx.getErrorCode() == 20006) {
            ex.setCodigoErrorAdministrador(jdbcEx.getErrorCode());
            ex.setSentenciaSQL(jdbcEx.getSQL());
            ex.setMensajeErrorUsuario("Error. El campo telefono es un campo numerico de 9 caracteres");
            ex.setMensajeErrorAdministrador(jdbcEx.getMessage());
        }
        throw ex;
    } catch (StaleStateException ssEx) {
        ExceptionMotor ex = new ExceptionMotor();

        ex.setMensajeErrorUsuario("Error. No existe ese cliente");

        throw ex;
    } catch (Exception e) {
        ExceptionMotor ex = new ExceptionMotor();

        ex.setCodigoErrorAdministrador(0);
        ex.setMensajeErrorUsuario("Error general en el sistema, Consulte con el administrador");
        ex.setMensajeErrorAdministrador(e.getMessage());

        throw ex;
    }

}

From source file:motor.MOTOR.java

/**
 * Mtodo que inserta un registro en la tabla coche. Utiliza operaciones
 * elementales/*w w  w  .ja  va 2  s.  co  m*/
 *
 * @param coche El objeto coche
 * @throws ExceptionMotor excepcion que integra el mensaje de error al
 * usuario, el codigo de error y el mensaje de error que nos ha devuelto la
 * base de datos
 */
public void insertarCoche(Coche coche) throws ExceptionMotor {
    // Se inicia una transaccin en la sesin creada
    Transaction t = sesion.beginTransaction();

    try {

        sesion.save(coche);
        // Se confirma la transaccin
        t.commit();
    } catch (PropertyValueException pvEx) {
        ExceptionMotor ex = new ExceptionMotor();

        ex.setMensajeErrorUsuario("Error. Todos los campos son obligatorios");
        ex.setMensajeErrorAdministrador(pvEx.getMessage());

        throw ex;

    } catch (ConstraintViolationException igEx) {
        ExceptionMotor ex = new ExceptionMotor();

        if (igEx.getErrorCode() == 2291) {
            ex.setCodigoErrorAdministrador(igEx.getErrorCode());
            ex.setSentenciaSQL(igEx.getSQL());
            ex.setMensajeErrorUsuario("Error. No existe ese cliente");
            ex.setMensajeErrorAdministrador("VIOLACION DE CHECK CONSTRAINT");
        } else if (igEx.getErrorCode() == 1) {
            ex.setCodigoErrorAdministrador(igEx.getErrorCode());
            ex.setSentenciaSQL(igEx.getSQL());
            ex.setMensajeErrorUsuario("Error. Los siguientes campos son unicos: matricula");
            ex.setMensajeErrorAdministrador("VIOLACION DE UNIQUE KEY");
        }
        throw ex;

    } catch (GenericJDBCException gjdbcEx) {
        ExceptionMotor ex = new ExceptionMotor();

        if (gjdbcEx.getErrorCode() == 20002) {
            ex.setCodigoErrorAdministrador(gjdbcEx.getErrorCode());
            ex.setSentenciaSQL(gjdbcEx.getSQL());
            ex.setMensajeErrorUsuario("Error. La ITV debe estar pasada");
            ex.setMensajeErrorAdministrador("VIOLACION DE TRIGGER ITV_PASADA");
        }
        if (gjdbcEx.getErrorCode() == 20004) {
            ex.setCodigoErrorAdministrador(gjdbcEx.getErrorCode());
            ex.setSentenciaSQL(gjdbcEx.getSQL());
            ex.setMensajeErrorUsuario("Error. El taller esta cerrado");
            ex.setMensajeErrorAdministrador("VIOLACION DE TRIGGER TALLER_ABIERTO");
        }
        throw ex;

    } catch (Exception e) {
        ExceptionMotor ex = new ExceptionMotor();

        ex.setCodigoErrorAdministrador(0);
        ex.setMensajeErrorUsuario("Error general en el sistema, Consulte con el administrador");
        ex.setMensajeErrorAdministrador(e.getMessage());

        throw ex;
    }

}

From source file:motor.MOTOR.java

/**
 * Mtodo que modifica los datos de un coche ya existente. Usa HQL
 * parametrizado//from   w  w w .j  a v a  2 s.  c  o  m
 *
 * @return el numero de registros afectados
 * @param coche el objeto coche con los datos a modificar
 * @throws ExceptionMotor excepcion que integra el mensaje de error al
 * usuario, el codigo de error y el mensaje de error que nos ha devuelto la
 * base de datos
 */
public int modificarCoche(Coche coche) throws ExceptionMotor {
    int registrosAfectados = -1;

    // Se inicia una transaccin en la sesin creada
    Transaction t = sesion.beginTransaction();

    // Se crea la query HQL
    Query q = sesion.createQuery("update Coche set cliente.clienteId = :coclienteId,"
            + "marca = :comarca, modelo = :comodelo, matricula = :comatricula , " + "itv = :coitv "
            + "where cocheId = :cococheId");
    q.setString("comarca", coche.getMarca());
    q.setString("comodelo", coche.getModelo());
    q.setString("comatricula", coche.getMatricula());
    q.setDate("coitv", coche.getItv());
    q.setBigDecimal("cococheId", coche.getCocheId());
    q.setBigDecimal("coclienteId", coche.getCliente().getClienteId());

    try {
        // Se ejecuta la query q
        registrosAfectados = q.executeUpdate();

        // Se confirma la transaccin
        t.commit();
    } catch (GenericJDBCException jdbcEx) {
        ExceptionMotor ex = new ExceptionMotor();

        if (jdbcEx.getErrorCode() == 2291) {
            ex.setCodigoErrorAdministrador(jdbcEx.getErrorCode());
            ex.setSentenciaSQL(jdbcEx.getSQL());
            ex.setMensajeErrorUsuario("Error. No existe ese ciente");
            ex.setMensajeErrorAdministrador("NO SE HA INTRODUCIDO UN COCHE_ID QUE EXISTA");
        }
        if (jdbcEx.getErrorCode() == 1407) {
            ex.setCodigoErrorAdministrador(jdbcEx.getErrorCode());
            ex.setSentenciaSQL(jdbcEx.getSQL());
            ex.setMensajeErrorUsuario(
                    "Error. Los siguientes campos son obligastorios: marca, modelo, matricula, itv");
            ex.setMensajeErrorAdministrador("VIOLACION DE NOT_NULL");
        }
        if (jdbcEx.getErrorCode() == 20002) {
            ex.setCodigoErrorAdministrador(jdbcEx.getErrorCode());
            ex.setSentenciaSQL(jdbcEx.getSQL());
            ex.setMensajeErrorUsuario("Error. La ITV debe estar pasada");
            ex.setMensajeErrorAdministrador("VILACION DE TRIGGER ITV_PASADA");
        }
        if (jdbcEx.getErrorCode() == 20004) {
            ex.setCodigoErrorAdministrador(jdbcEx.getErrorCode());
            ex.setSentenciaSQL(jdbcEx.getSQL());
            ex.setMensajeErrorUsuario("Error. El taller esta cerrado");
            ex.setMensajeErrorAdministrador("VIOLACION DE TRIGGER TALLER ABIERTO");
        }
        throw ex;
    } catch (ConstraintViolationException cvEx) {
        ExceptionMotor ex = new ExceptionMotor();

        if (cvEx.getErrorCode() == 1) {
            ex.setCodigoErrorAdministrador(cvEx.getErrorCode());
            ex.setSentenciaSQL(cvEx.getSQL());
            ex.setMensajeErrorUsuario("Error. El campo matricula es unico");
            ex.setMensajeErrorAdministrador("VIOLACION DE UNIQUE KEY");
        }
        throw ex;
    } catch (StaleStateException ssEx) {
        ExceptionMotor ex = new ExceptionMotor();

        ex.setMensajeErrorUsuario("Error. No existe ese coche");
        ex.setMensajeErrorAdministrador("SE HA INTRODUCIDO UN COCHE_ID QUE NO EXISTE");
        throw ex;
    } catch (Exception e) {
        ExceptionMotor ex = new ExceptionMotor();

        ex.setCodigoErrorAdministrador(0);
        ex.setMensajeErrorUsuario("Error general en el sistema, Consulte con el administrador");
        ex.setMensajeErrorAdministrador(e.getMessage());

        throw ex;
    }
    return registrosAfectados;
}

From source file:org.candlepin.util.RdbmsExceptionTranslator.java

License:Open Source License

public boolean isConstraintViolationDuplicateEntry(PersistenceException pe) {
    log.debug("Translating {}", pe);

    if (pe.getCause() != null && pe.getCause() instanceof ConstraintViolationException) {

        ConstraintViolationException cve = (ConstraintViolationException) pe.getCause();
        log.info("ConstraintViolationException error code:" + cve.getErrorCode());

        //MySQL error code ER_DUP_ENTRY
        //http://dev.mysql.com/doc/refman/5.7/en/error-messages-server.html
        if (cve.getSQLState() != null && cve.getSQLState().equals("23000") && cve.getErrorCode() == 1062) {
            return true;
        }//from   w ww.  j  a  v  a2s  . c om

        //Postgres error code DUPLICATE OBJECT
        //https://www.postgresql.org/docs/8.3/static/errcodes-appendix.html
        if (cve.getSQLState() != null && cve.getSQLState().equals("23505")) {
            return true;
        }

        //TODO add Oracle
    }
    return false;
}

From source file:org.seamless.gwt.server.HibernateRemoteServiceServlet.java

License:Open Source License

@Override
protected String onBeforeResponseSerialized(Object result) {
    if (!getCurrentSession().getTransaction().isActive())
        return null;

    try {/*from   w  w  w.  java 2 s .com*/
        // Commit and cleanup
        log.fine("Committing the database transaction");
        getCurrentSession().getTransaction().commit();

    } catch (RuntimeException ex) {
        // Rollback only
        log.fine("Runtime exception occurred, considering transaction rollback: " + ex);
        try {
            if (getCurrentSession().getTransaction().isActive()) {
                log.fine("Trying to rollback database transaction after exception");
                getCurrentSession().getTransaction().rollback();
                log.fine("Transaction rolled back");
            }
        } catch (Throwable rbEx) {
            log.log(Level.SEVERE, "Could not rollback transaction after exception!", rbEx);
        }

        // Note that the exception you marshall to the client has to be
        // serializable/cross-compiled (in your 'shared'  or 'client' package)
        // and it has to implement com.google.gwt.user.client.rpc.IsSerializable
        // to pass the serialization policy security.

        if (ex instanceof StaleObjectStateException) {
            StaleObjectStateException sosEx = (StaleObjectStateException) ex;
            log.fine("Stale object state detected, serializing message to client for: " + sosEx);

            StringBuilder sb = new StringBuilder();
            sb.append("Concurrent modification error, ");
            sb.append("simultaneous modification of '").append(sosEx.getEntityName()).append("'");
            sb.append(" with identifier: ").append(sosEx.getIdentifier());

            ValidationException serializableException = new ValidationException(sb.toString());
            try {
                return encodeResponseForFailure(null, serializableException);
            } catch (SerializationException e) {
                log.fine("Can't serialize concurrent modification error message: " + e);
                throw ex;
            }

        }

        if (ex instanceof ConstraintViolationException) {
            ConstraintViolationException cvEx = (ConstraintViolationException) ex;
            log.fine("Integrity constraint violation detected, serializing message to client for: " + cvEx);

            StringBuilder sb = new StringBuilder();
            sb.append("Violation of database integrity, ");
            sb.append("error code: ").append(cvEx.getErrorCode());
            ValidationException serializableException = new ValidationException(sb.toString());
            try {
                return encodeResponseForFailure(null, serializableException);
            } catch (SerializationException e) {
                log.fine("Can't serialize integrity rule violation message: " + e);
                throw ex;
            }
        } else {
            throw ex;
        }
    }
    return null;
}