I suppose this must be a very basic question.
I relaunch this code which tries to insert an already existing row in a table but the ConstraintViolationException is catched in the general catch (Exception e) block insted of being catched in the specific catch (ConstraintViolationException e) block as I expected.
I wonder what should I try to catch that specific exception.
My code:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.exception.ConstraintViolationException;
import clases.Departamentos;
import util.HibernateUtil;
 
public class InsertarDepartamento {
 
    public static void main(String[] args) {
        //obtenemos la sesión actual
        SessionFactory sf = HibernateUtil.getSessionFactory();
        //creamos la sesión
        Session s = sf.openSession();
        Transaction tx = null;
                 
        try {
            //creamos una transacción en la sesión
            tx = s.beginTransaction();
            System.out.println("Vamos insertar una nueva fila en la tabla Departamentos");
            Departamentos dep = new Departamentos();
            dep.setNumero(3);
            dep.setNombre("Marketing");
             
            try {
                s.save(dep); //hacemos persistente el objeto departamento creado            
            } catch (ConstraintViolationException e) {
                System.err.println(e);
            }           
            tx.commit(); // javax.persistence.EntityTransaction;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            if (tx != null) {
                tx.rollback();
            }
        } finally {
            s.close();          
        }       
    }
 
}
My console output:
Vamos insertar una nueva fila en la tabla Departamentos nov 18, 2022 1:10:26 A. M. org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions WARN: SQL Error: 1062, SQLState: 23000 nov 18, 2022 1:10:26 A. M. org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions ERROR: Duplicate entry '3' for key 'departamentos.PRIMARY' nov 18, 2022 1:10:26 A. M. org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release INFO: HHH000010: On release of batch it still contained JDBC statements org.hibernate.exception.ConstraintViolationException: could not execute statement
I am editting the question following some suggestions in the comments. I have seen two things:
- I was assuming it was the save method which launched the ConstraintViolationException but in fact it is the commit method which launches it
- I can catch PersistenceException (not ConstraintViolationException)
I wonder if this code would be acceptable:
import javax.persistence.PersistenceException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.exception.ConstraintViolationException;
import clases.Departamentos;
import util.HibernateUtil;
public class InsertarDepartamento {
    public static void main(String[] args) {
        //obtenemos la sesión actual
        SessionFactory sf = HibernateUtil.getSessionFactory();
        //creamos la sesión
        Session s = sf.openSession();
        Transaction tx = null;
                
        try {
            //creamos una transacción en la sesión
            tx = s.beginTransaction();
            System.out.println("Vamos insertar una nueva fila en la tabla Departamentos");
            Departamentos dep = new Departamentos();
            dep.setNumero(3);
            dep.setNombre("Marketing");
            
            try {
                s.save(dep); //hacemos persistente el objeto departamento creado
                tx.commit(); // javax.persistence.EntityTransaction;
            } catch (ConstraintViolationException e) {
                System.out.println("ConstraintViolationException: "+e.getMessage());
                //e.printStackTrace();
            } catch (PersistenceException e) {
                System.out.println("PersistenceException: "+e.getMessage());
                //e.printStackTrace();
            }           
        } catch (Exception e) {
            //System.out.println(e.getMessage());
            //System.out.println(e.getCause());
            //System.out.println(e.getStackTrace());
            e.printStackTrace();
        } finally {
            if (tx != null) {
                tx.rollback();
            }           
            s.close();          
        }       
    }
}
Which causes this new output:
Vamos insertar una nueva fila en la tabla Departamentos nov 18, 2022 9:54:59 A. M. org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions WARN: SQL Error: 1062, SQLState: 23000 nov 18, 2022 9:54:59 A. M. org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions ERROR: Duplicate entry '3' for key 'departamentos.PRIMARY' nov 18, 2022 9:54:59 A. M. org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release INFO: HHH000010: On release of batch it still contained JDBC statements PersistenceException: org.hibernate.exception.ConstraintViolationException: could not execute statement
 
    
