These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 
Author Message
 Post subject: org.hibernate.exception.ConstraintViolationException
PostPosted: Wed Sep 09, 2009 1:09 pm 
Newbie

Joined: Fri Oct 31, 2008 11:35 am
Posts: 12
Hi everyone!!!


I have an application with hibernate and other with JDBC, bouth inserts in the same table in any moment. My problem is in my Hibernate application I get this exception:

org.hibernate.exception.ConstraintViolationException, beacuse it is traying to use an id that already exists because jdbc application used it.

When this happend, I´m trying to refresh the id with this code:

Code:
try{
//inserts
}
} catch (Exception ex) {
                sessionL.getTransaction().rollback();
                if(ex instanceof org.hibernate.exception.ConstraintViolationException){
                    try{
                        if(sessionL != null && sessionL.isOpen() && sessionL.isDirty())
                            sessionL.clear();
                        if(sessionL != null && sessionL.isOpen())
                            sessionL.close();
                        if(sessionL != null && sessionL.isConnected())
                            sessionL.disconnect();
                        Thread.sleep(5000);
                    }catch(Exception thex){
                        System.out.println("No se logro completar la pausa en los intentos de confirmacion Q");
                    }
                }
            } finally {
                intentos ++;
                if (sessionL!= null && sessionL.isOpen()) {
                    sessionL.close();
                    sessionL = null;
                }
            }
        }while(intentos < 10);




How can i refresh or synchronize my id in hibernate with the other application???



this is my whole method, thanks


Code:
public synchronized void confirmaMovimientoQ(ActionEvent event) { //método sincronizado para evitar insertar simultaneamente
        int intentos = 0;
        Session sessionL = null;
        opcionPopup = "ConsIntentos";
                        this.mensajePopup = "Solicitando consecutivo a sistema... reintento en 5 segs. \r\n Espere por favor...";
        /*el movimiento no responde a ninguna cuenta de origen*/
        currentArchivoQ.setCuentaOrigen(""); //responde a la cuenta del usuario que la generó al recibir firma
        currentArchivoQ.setFecha(new Date());
        currentArchivoQ.setTipo('Q');
        /***/
        String aux = "";
        Utileria utaux = new Utileria();
        //calcula el ultimo folio Q para el nuevo archivo
        do{
            utileria = (Utileria)cargaObjetoCC(utileria);
            utileria.setConsecutivoQ(((utileria.getConsecutivoQ() + 1) > 1000) ? 1 : (utileria.getConsecutivoQ() + 1));
            utaux = (Utileria)cargaObjetoCC(utileria);

            if(utileria.getConsecutivoQ() != utaux.getConsecutivoQ()){
                sessionL = HibernateUtil.getSessionFactory().getCurrentSession();
                sessionL.beginTransaction();
                sessionL.clear();
                sessionL.update(utileria);
                sessionL.getTransaction().commit();
                if(sessionL.isOpen()){
                    sessionL.flush();
                    sessionL.close();
                }
                aux = String.valueOf(utileria.getConsecutivoQ());
                break;
            }
            else{
                try{
                    System.out.println("Reintentando calcular consecutivo...");
                    Thread.sleep(1000);
                }catch(Exception tex){
                    tex.printStackTrace();
                    continue;
                }
            }
        }while(true);

        /*transaccion de registro de archivo Q*/
        do{
            try {
                //registra archivo Q
                while (aux.length() < 3) {
                    aux = "0" + aux;
                }
                this.currentArchivoQ.setNombre(this.currentArchivoQ.getNombre().replace("XXX", aux));
                //crea un nuevo objeto archivo a partir del creado en el editor
                Archivo newQ = new Archivo();
                newQ.setCuentaOrigen(this.currentArchivoQ.getCuentaOrigen());
                newQ.setFecha(this.currentArchivoQ.getFecha());
                newQ.setIdUsuario(this.currentArchivoQ.getIdUsuario());
                newQ.setNombre(this.currentArchivoQ.getNombre());
                newQ.setTipo(this.currentArchivoQ.getTipo());
                newQ.setRegistros(new TreeSet());
                //crea los objetos registro del archivo
                for(Object registro:this.currentArchivoQ.getRegistros()){
                    Registro reg = (Registro)registro;
                    Registro newR = new Registro();
                    newR.setArchivo(newQ);
                    newR.setLinea(reg.getLinea());
                    newR.setVisible(reg.isVisible());
                    newR.setCampos(new TreeSet());
                    //crea los objetos campo del archivo
                    for(Object campo:reg.getCampos()){
                        Campo cam = (Campo)campo;
                        Campo newC = new Campo();
                        newC.setRegistro(newR);
                        newC.setNombre(cam.getNombre());
                        newC.setNum(cam.getNum());
                        newC.setTamano(cam.getTamano());
                        newC.setTipo(cam.getTipo());
                        newC.setValor(cam.getValor());
                        newR.getCampos().add(newC);
                    }
                    newQ.getRegistros().add(newR);
                }

                //obtiene sesion para transaccion
                sessionL = HibernateUtil.getSessionFactory().getCurrentSession();
                //inicia transaccion para confirmacion de movimiento Q
                sessionL.beginTransaction();
                sessionL.clear();
                sessionL.save(newQ);
                sessionL.flush();
                //registrar movimiento Q
                DetalleMovimiento nuevoDetalle = new DetalleMovimiento();
                nuevoDetalle.setFolio(this.currentCartaCupo.getFolio());
                nuevoDetalle.setFechaMovimiento(new Date());
                nuevoDetalle.setMovimiento(this.currentMovimientoQ);
                nuevoDetalle.setArchivo(newQ);
                nuevoDetalle.setFirmaElectronica("N/C");

                //calcula consecutivo de detalleMovimiento
                int consMov = 0;
                Query q = sessionL.createQuery("SELECT MAX(idDetalleMovimiento) FROM DetalleMovimiento WHERE folio =:idCC");
                q.setLong("idCC", currentCartaCupo.getFolio());
                List sResultc = q.list();
                if (sResultc.size() == 0) {
                    consMov = 0;
                } else {
                    for (Object x : sResultc) {
                        consMov = ((Integer) x).intValue() + 1;
                    }
                }

                nuevoDetalle.setIdDetalleMovimiento(consMov);
                sessionL.save(nuevoDetalle);
                sessionL.flush();
                //en movimientos AI salva REO
                if(this.currentMovimientoQ.getClaveMovimiento().trim().equals("AI") ||
                   this.currentMovimientoQ.getClaveMovimiento().trim().equals("AIT")){
                    for(Object r:this.getCurrentArchivoQ().getRegistros()){
                        Iterator itc = ((Registro)r).getCampos().iterator();
                        while(itc.hasNext()){
                            Campo cam = (Campo)itc.next();
                            if(cam.getValor().trim().equals("REO"))
                                this.currentCartaCupo.setRegistroEntradaOriginal(((Campo)itc.next()).getValor());
                        }
                    }
                    sessionL.update(this.currentCartaCupo);
                    sessionL.flush();
                }
                sessionL.getTransaction().commit();
                //finaliza transaccion para confirmacion de movimiento Q
                if (sessionL!= null && sessionL.isOpen()) {
                    sessionL.flush();
                    sessionL.close();
                    sessionL = null;
                }
                buscaUltimoMovimientoCC(currentCartaCupo);
                Properties prop = new Properties();
                //java.io.InputStream is = new FileInputStream("\\\\192.178.1.209\\D\\CAA.properties");
                java.io.InputStream is = new FileInputStream("c:\\CAA.properties");
                prop.load(is);
                String dirSQ = prop.getProperty("dirSalida_Q");
                try {
                    File repuesta = new File(dirSQ + newQ.getNombre());
                    FileWriter fw = new FileWriter(repuesta);
                    fw.write(newQ.toString());
                    fw.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
                vuelveCC();
                intentos = 0;
                this.setVisible(false);
                break; //rompe el while de intentos
            } catch (Exception ex) {
                //ex.printStackTrace();
                sessionL.getTransaction().rollback();
                System.out.println(ex.getClass());
                if(ex instanceof org.hibernate.exception.ConstraintViolationException){
                    try{
                        this.openPopup();
                        if(sessionL != null && sessionL.isOpen() && sessionL.isDirty())
                            sessionL.clear();
                        if(sessionL != null && sessionL.isOpen())
                            sessionL.close();
                        if(sessionL != null && sessionL.isConnected())
                            sessionL.disconnect();
                        Thread.sleep(5000); //espera un par de segundos antes de reintentar la transaccion
                    }catch(Exception thex){
                        System.out.println("No se logro completar la pausa en los intentos de confirmacion Q");
                        //thex.printStackTrace();
                    }
                }
            } finally {
                intentos ++;
                if (sessionL!= null && sessionL.isOpen()) {
                    sessionL.close();
                    sessionL = null;
                }
            }
        }while(intentos < 10);// while intentos > 3
    }



Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 1 post ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.