🔴 The Error You're Seeing
Confirm this matches your console output. If it does, you're in the right place.
2026-02-14 15:05:55.800 ERROR 8842 --- [nio-8080-exec-7] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]] with root cause
java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'admin@devinhyderabad.com' for key 'uk_email'⚡ Quick Fix Works 80% of the time
Check if the record exists before saving, or catch the DataIntegrityViolationException globally.
if (userRepository.existsByEmail(email)) {
throw new ResourceNotFoundException("Email already in use");
}
userRepository.save(user);🧠 Why this Happens
Tap to expand the deep technical explanation
Your database table has a unique constraint (like a primary key or a unique index on an email column). You tried to INSERT or UPDATE a row with a value that is already used by another row, violating the uniqueness rule.
The HITEC City Parking Spot Analogy:
It is like two people trying to claim the exact same phone number. The phone company (database) rejects the second person because a number can only belong to one account.
🔁 How to Reproduce Confirm this is your error
Save a user whose email already exists under a UNIQUE constraint, without checking for an existing record first. The save throws Duplicate entry '...' for key 'uk_email'.
🛠️ Solutions (3 Ways to Fix)
Check for existence before saving
👉 Use this for simple checks where you want to return a clean 400 error to the user.
Query the database to see if the unique field already exists. If it does, throw a custom exception instead of letting it hit the DB constraint.
@Service
public class UserService {
public User createUser(UserRequest req) {
if (repo.existsByEmail(req.getEmail())) {
throw new EmailAlreadyExistsException("Email is taken");
}
return repo.save(new User(req));
}
}Catch DataIntegrityViolationException globally
👉 Use this as a fallback to prevent 500 errors if the existence check is bypassed (race condition).
Create a global exception handler that catches the constraint violation and returns a 409 Conflict status.
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(DataIntegrityViolationException.class)
public ResponseEntity<String> handleDuplicateEntry(DataIntegrityViolationException ex) {
return ResponseEntity.status(HttpStatus.CONFLICT).body("Resource already exists");
}
}Add @UniqueConstraint to your Entity
👉 Use this if the database doesn't actually have the unique constraint set up yet.
Explicitly declare the unique constraint on the Entity class so Hibernate generates the proper DB schema.
@Entity
@Table(name = "users", uniqueConstraints = {
@UniqueConstraint(columnNames = "email")
})
public class User { ... }📋 Version Notes
Throws DataIntegrityViolationException.
Throws DataIntegrityViolationException, often wrapping jakarta.persistence.PersistenceException.
🛡️ How to Prevent This Next Time
Implement existence checks in your service layer for all unique fields, and rely on DB constraints as a final safety net.