How can i catch this Exception :
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '22-85' for key 'ID_CONTACT'
Use the INSERT IGNORE command rather than the INSERT command. If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error.
The DuplicateKeyException exception is thrown if an entity EJB object or EJB local object cannot be created because an object with the same key already exists. This exception is thrown by the create methods defined in an entity bean's home or local home interface.
The easiest way is to designate the primary key as UNIQUE. Be sure to check the return value of your insert commands as then the server will reject the duplicates.
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.
catch SQLIntegrityConstraintViolationException, if you are using Java 1.6+
e.g.
try { ps.executeUpdate("INSERT INTO ..."); } catch (SQLIntegrityConstraintViolationException e) { // Duplicate entry } catch (SQLException e) { // Other SQL Exception }
or
try { ps.executeUpdate("INSERT INTO ..."); } catch (SQLException e) { if (e instanceof SQLIntegrityConstraintViolationException) { // Duplicate entry } else { // Other SQL Exception } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With