Example usage for org.hibernate.exception GenericJDBCException getErrorCode

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

Introduction

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

Prototype

public int getErrorCode() 

Source Link

Document

Get the vendor specific error code from the underlying SQLException .

Usage

From source file:motor.MOTOR.java

/**
 * Mtodo que inserta una registro en la tabla cliente. Utiliza operaciones
 * elementales//  w ww.j  a  v a  2 s.c o  m
 *
 * @param cliente el coche a insertar
 * @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 insertarCliente(Cliente cliente) throws ExceptionMotor {
    // Se inicia una transaccin en la sesin creada
    Transaction t = sesion.beginTransaction();

    try {

        sesion.save(cliente);
        // Se confirma la transaccin
        t.commit();
    } catch (IdentifierGenerationException igEx) {
        ExceptionMotor ex = new ExceptionMotor();
        throw ex;
    } catch (ConstraintViolationException igEx) {
        ExceptionMotor ex = new ExceptionMotor();
        if (igEx.getErrorCode() == 2290) {
            ex.setCodigoErrorAdministrador(igEx.getErrorCode());
            ex.setSentenciaSQL(igEx.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(igEx.getMessage());
        } else {
            ex.setCodigoErrorAdministrador(igEx.getErrorCode());
            ex.setSentenciaSQL(igEx.getSQL());
            ex.setMensajeErrorUsuario("Error. Los siguientes campos son nicos: dni, email y telefono");
            ex.setMensajeErrorAdministrador(igEx.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 campo 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 (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 ww  .  java 2 s . c o 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/*from  w ww  .j a  va 2  s.  c o 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//  w  ww  .j av  a  2 s  .co 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:vista.departamentos.UpdateDepart.java

License:Open Source License

/**
 * Cargo la ventana con sus controles.//from   ww  w.j a v a 2s  .c om
 *
 */
private void loadWindows() {
    Dimension dimen = new Dimension(630, 380);
    setSize(dimen);
    setPreferredSize(dimen);
    setMinimumSize(dimen);
    setMaximumSize(dimen);
    //Para cuando cierran la ventana, no sea visible
    setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);

    //Lo que puede realizar la ventana
    setResizable(false);
    setClosable(true);
    setIconifiable(true);

    //Aado el listener del foco
    addFocusListener(new FocoListener());

    //Head
    accionLabel.setFont(new Font("Arial", Font.BOLD, 27));

    //Etiquetas
    codigoLabel = new JLabel("Codigo");
    codigoLabel.setFont(new Font("Arial", Font.PLAIN, 15));
    nombreLabel = new JLabel("Nombre");
    nombreLabel.setFont(new Font("Arial", Font.PLAIN, 15));
    locLabel = new JLabel("Localidad");
    locLabel.setFont(new Font("Arial", Font.PLAIN, 15));

    /* Campos */

    //Codigo
    codigoField = new JTextField(5);
    codigoField.setFont(new Font("Arial", Font.PLAIN, 15));
    //No te deja poner el foco en otro sitio hasta que no sea valido
    codigoField.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            verificarCodigoField();
        }
    });

    //Nombre
    nombreField = new JTextField(10);
    nombreField.setFont(new Font("Arial", Font.PLAIN, 15));
    nombreField.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            verificarNombreField();
        }
    });

    //Si el titulo de la ventana es de Alta que se pueda editar
    nombreField.setEditable(accion.equals(ALTA));

    //Localidad
    locField = new JTextField(10);
    locField.setFont(new Font("Arial", Font.PLAIN, 15));
    locField.setEditable(accion.equals(ALTA));

    //Mensajes 
    messageLabel = new JTextField(30);
    messageLabel.setFont(new Font("Arial", Font.BOLD, 15));
    messageLabel.setHorizontalAlignment(JTextField.CENTER);
    messageLabel.setPreferredSize(new Dimension(100, 50));
    messageLabel.setEditable(false);

    //Botones
    consultar = new JButton("Consultar");
    consultar.setFont(new Font("Arial", Font.BOLD, 12));
    consultar.setPreferredSize(new Dimension(90, 50));
    consultar.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                if (verificarCodigoField()) {
                    consultar(Integer.parseInt(codigoField.getText()));
                } else {
                    codigoField.requestFocus();
                }
            } catch (SQLException sqle) {
                mostrarMensaje("** Error en la base de datos **");
            }
        }
    });

    if (accion.equals(MODIFICAR)) {
        accionBtn.setFont(new Font("Arial", Font.BOLD, 12));
    } else {
        accionBtn.setFont(new Font("Arial", Font.BOLD, 20));
    }
    accionBtn.setPreferredSize(new Dimension(90, 50));
    accionBtn.setEnabled(false);
    accionBtn.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                switch (accion) {
                case ALTA:
                    alta(Integer.parseInt(codigoField.getText()), nombreField.getText(), locField.getText());
                    break;
                case BAJA:
                    baja(Integer.parseInt(codigoField.getText()));
                    break;
                case MODIFICAR:
                    if (esCadena(nombreField.getText())) {
                        //No pasa nada si la localidad es nula
                        if (esCadena(locField.getText()) || locField.getText().length() == 0) {
                            modificar(Integer.parseInt(codigoField.getText()), nombreField.getText(),
                                    locField.getText());
                            codigoField.setEnabled(true);
                        } else {
                            mostrarMensaje("** Ponga una localidad correcta **");
                            accionBtn.setEnabled(false);
                        }
                    } else {
                        mostrarMensaje("** Introduzca un nombre de " + "departamento **");
                        accionBtn.setEnabled(false);
                    }
                    break;
                }
                accionBtn.setEnabled(false);
            } catch (GenericJDBCException bue) {
                sucedioError(bue.getErrorCode());
            } catch (SQLException sqle) {
                sucedioError(sqle.getErrorCode());
            }
        }
    });

    //Paneles
    titulo = new JPanel(new FlowLayout());
    titulo.add(accionLabel);
    titulo.setBackground(new Color(197, 217, 237));

    //Aadir botones
    botones = new JPanel(new BorderLayout());
    botones.add(consultar, BorderLayout.NORTH);
    botones.add(accionBtn, BorderLayout.SOUTH);

    formulario = new JPanel(new GridBagLayout());
    gridCons = new GridBagConstraints();
    //Espacioes entre componentes
    gridCons.insets = new Insets(20, 20, 20, 20);
    //Todos pegados a la izquierda
    gridCons.anchor = GridBagConstraints.LINE_START;

    //Row1
    addGridBag(codigoLabel, 0, 0);
    addGridBag(codigoField, 1, 0);
    gridCons.gridheight = 5;
    gridCons.fill = GridBagConstraints.BOTH;
    addGridBag(botones, 2, 0);
    gridCons.gridheight = 1;
    gridCons.fill = GridBagConstraints.NONE;
    //Row2
    addGridBag(nombreLabel, 0, 1);
    addGridBag(nombreField, 1, 1);
    //Row3
    addGridBag(locLabel, 0, 2);
    addGridBag(locField, 1, 2);
    //Row4
    gridCons.anchor = GridBagConstraints.CENTER;
    gridCons.fill = GridBagConstraints.BOTH;
    gridCons.ipadx = 40;
    gridCons.gridwidth = 2;
    gridCons.gridheight = 2;
    addGridBag(messageLabel, 0, 3);

    //Lo aado a la ventana que contiene todos los compotentes
    window = new JPanel(new BorderLayout());

    window.add(titulo, BorderLayout.NORTH);
    window.add(formulario, BorderLayout.CENTER);

    //Aado la ventana al contenedor con espacios
    gridCons = new GridBagConstraints();
    gridCons.insets = new Insets(0, 20, 10, 20);

    contenedor.setLayout(new GridBagLayout());
    contenedor.setBackground(new Color(197, 217, 237));
    contenedor.add(window, gridCons);

    //Por defecto pongo el boton de consultar
    getRootPane().setDefaultButton(consultar);
}