Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch duplicate entry Exception

How can i catch this Exception :

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:                                        Duplicate entry '22-85' for key 'ID_CONTACT' 
like image 960
Hayi Avatar asked Dec 20 '14 17:12

Hayi


People also ask

How do I ignore duplicate entries?

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.

What is duplicate key exception?

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.

How can we avoid inserting duplicate records in MySQL using Java?

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.


2 Answers

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.

like image 103
Hayi Avatar answered Sep 19 '22 13:09

Hayi


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     } } 
like image 23
auntyellow Avatar answered Sep 19 '22 13:09

auntyellow