Catch duplicate entry Exception

Youssef picture Youssef · Dec 20, 2014 · Viewed 89.7k times · Source

How can i catch this Exception :

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

Answer

Youssef picture Youssef · Dec 20, 2014

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.