hibernate: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException
        Posted  
        
            by 
                user121196
            
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by user121196
        
        
        
        Published on 2012-09-16T09:35:47Z
        Indexed on 
            2012/09/16
            9:37 UTC
        
        
        Read the original article
        Hit count: 254
        
when saving an object to database using hibernate, sometimes it fails because certain fields of the object exceed the maximum varchar length defined in the database.  There force I am using the following approach:
1. attempt to save
2. if getting an DataException, then I truncate the fields in the object to the max length specified in the db definition, then try to save again.
However, in the second save after truncation.  I'm getting the following exception:
hibernate: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails
here's the relevant code, what's wrong?
  public static void saveLenientObject(Object obj){
        try {
            save2(rec);
        } catch (org.hibernate.exception.DataException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            saveLenientObject(rec, e);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    private static void saveLenientObject(Object rec, DataException e) {
        Util.truncateObject(rec);
        System.out.println("after truncation ");
        save2(rec);
    }
    public static void save2(Object obj) throws Exception{
        try{
            beginTransaction();
            getSession().save(obj);
            commitTransaction();
        }catch(Exception e){
            e.printStackTrace();
            rollbackTransaction();
            //closeSession();
            throw e;
        }finally{
            closeSession(); 
        }
    }    
        © Stack Overflow or respective owner