1

When saving an object to database using hibernate, it sometimes fails because of certain fields in the object exceeding the maximum varchar length defined in the database.

Therefore I am using the following approach:

  1. Attempt to save
  2. If getting an DataException, I then 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, do you notice anything wrong with it?

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(); 
    }
}    

2 Answers 2

1

All Hibernate exceptions (except for NonUniqueResultException) are irrecoverable. If you get an exception you should close the session and open another one for further operations.

See also:

Sign up to request clarification or add additional context in comments.

1 Comment

but I did roll back and then close the session. and then open a new session.
0

The hibernate documentaiton is quite clear that once an exception is thrown the session will be left in an inconsistent state so is not safe to use for further operations. I suspect that what you're getting here is that the session is left half saving your first attempt so bad things happen.

Fundamentally you should not rely on database errors to check the length of your fields, instead you should pre-validate this in java code. If you know the lengths enough to truncate, then I suggest you simply call your trucate util every time.

Alternatively use Hibernate Validator to declaratively validate the objects before saving.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.