Catch duplicate entry Exception

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.

Leave a Comment