Search code examples
javamysqlhibernatejpasqlexception

Catch duplicate entry Exception


How can i catch this Exception :

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: 
                                      Duplicate entry '22-85' for key 'ID_CONTACT'

Solution

  • I use spring so we resolve it by org.springframework.dao.DataIntegrityViolationException

    try {
        ao_history_repository.save(new AoHistory(..));
    } catch (DataIntegrityViolationException e) {
        System.out.println("history already exist");
    }
    

    But as @KevinGuancheDarias mention it:

    Please note that while this works. I suggest to solve the problem by issuing a findBy before the save, as this is messy, and I think it's not warranted that it will work in future versions, may even break without notification.