Primary Key Conflicts & ClassNotFound: 1-Minute Debugging Guide to Save Hours

This article provides a systematic troubleshooting guide for two common production errors—primary key conflicts and class-not-found exceptions—covering error identification, one-minute root cause localization steps, practical fixes like ON DUPLICATE KEY UPDATE and dependency scope checks, and real-world prevention tips.

Engineer Tang's Implementation Study Notes
Engineer Tang's Implementation Study Notes
Engineer Tang's Implementation Study Notes
Primary Key Conflicts & ClassNotFound: 1-Minute Debugging Guide to Save Hours

Primary Key Conflict (Duplicate Entry)

1. Error Scene

The core symptom: when inserting or updating data, the database throws a constraint violation because the value already exists in a primary key or unique index. Typical stack traces include

com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '12345' for key 'PRIMARY'

and

org.springframework.dao.DuplicateKeyException: Duplicate entry 'user_001' for key 'uk_cons_no'

. Seeing Duplicate entry or DuplicateKeyException confirms a primary key or unique index conflict.

2. One-Minute Localization

Three steps:

Extract conflict field, value, and index name from the log. Example: Duplicate entry '12345' for key 'PRIMARY' → primary key conflict, value 12345. Duplicate entry 'user_001' for key 'uk_cons_no' → unique index uk_cons_no conflict, value user_001.

Query the database to verify if the value already exists. For primary key: SELECT * FROM user WHERE id = 12345; For unique index: SELECT * FROM user WHERE cons_no = 'user_001'; Match the conflict type to common causes.

Primary Key Conflict (error identifier: PRIMARY): Manual primary key assignment, auto-increment sequence corruption, duplicate script execution.

Unique Index Conflict (error identifier: uk_custom_name): Duplicate business number submission, duplicate rows in batch import, sync script run twice.

3. Troubleshooting Guide

Verify conflicting data – Query DB by log field. Row exists = duplicate insertion.

Check primary key assignment logic – Inspect business code. Manual ID setting easily causes conflicts.

Verify pre-insert query exists – Check code or logs. No existence check = prone to duplicate inserts.

Audit scheduled tasks / sync scripts – Review execution records. Repeated runs cause batch duplicates.

Standard Solutions:

Prohibit manual primary key assignment – let the database auto-increment generate IDs.

Query before insert – if exists, update or skip; only insert if absent.

Use "insert on duplicate key update" syntax for high concurrency :

INSERT INTO user (cons_no, name, phone)
VALUES ('user_001', '张三', '13800138000')
ON DUPLICATE KEY UPDATE
  name = VALUES(name),
  phone = VALUES(phone);

Deduplicate before batch import – use Excel deduplication or SQL temp table deduplication (the author has a separate article on large-volume import).

Practical Experience: 85% of Primary Key Conflicts Stem from Non-Standard Manual Operations

The author recounts a case where testers hard-coded IDs for convenience; later the production auto-increment sequence collided with those manual rows, causing crashes. Another frequent scenario: re-running a data sync script that appeared to succeed but missed some rows; the second run hits existing data and triggers primary key conflicts.

When facing a primary key conflict, ask three questions:

Did I manually insert this conflicting row earlier?

Did the sync script or scheduled job run repeatedly?

Does the batch import source contain duplicate rows?

If any answer is yes, delete or modify the duplicate data yourself—no need to escalate to developers.

One-Sentence Summary: For primary key conflicts, check existing data first, disable manual custom IDs, query before insert. Most cases are self-inflicted operational errors—don't rush to blame others.

Class Not Found Exceptions (ClassNotFoundException / NoClassDefFoundError)

1. Error Scene

These two errors look similar but have completely different root causes:

// Case A: Class not found at compile time (missing dependency)
java.lang.ClassNotFoundException: com.xxx.utils.JsonUtils

// Case B: Compiles fine, but class file missing at runtime
java.lang.NoClassDefFoundError: org/apache/commons/lang3/StringUtils
ClassNotFoundException

→ The class was never included in project dependencies; local compilation fails. NoClassDefFoundError → Local compilation succeeds, but the class file is missing at runtime (packaging omission, JAR conflict, external dependency not loaded).

2. One-Minute Localization

Core principle: Distinguish the error type first, then investigate level by level —don't blindly search code or tweak configs.

ClassNotFoundException – Core characteristic: Class missing at both compile and runtime. Investigation direction: Check project dependency configuration (pom.xml / build.gradle).

NoClassDefFoundError – Core characteristic: Compiles OK, fails at class loading. Investigation direction: Check packaging artifact, JAR conflicts, external dependency paths.

Localization steps:

Read the reported class name – e.g., com.xxx.utils.JsonUtils – identify which package it belongs to.

Check dependencies – open pom.xml or build.gradle, search for that package.

Verify dependency scope – if scope is test or provided, the runtime environment won't include it; change to compile or runtime.

Unpack the deployment package – run jar -xf app.jar or unzip, inspect BOOT-INF/lib for the expected JAR. Absence means packaging omission.

If dependency is external – verify the startup script includes -Dloader.path pointing to the external lib directory.

3. Troubleshooting Guide

View project dependencies – Open pom.xml. Add missing dependency and rebuild.

Check dependency versions – mvn dependency:tree. Version mismatches may cause conflicts.

Unpack deployment package – jar -xf app.jar. Check BOOT-INF/lib for the JAR.

Inspect startup script – cat start.sh. Verify external dependency loaded via -Dloader.path.

Practical Fixes:

Missing dependency – add the required dependency in pom.xml, repackage and redeploy.

Multi-module version conflicts – unify versions or lock with dependencyManagement.

Packaging omission – verify spring-boot-maven-plugin configuration ensures complete packaging.

External dependency not loaded – add to startup command:

java -jar app.jar -Dloader.path=./lib-external/

Practical Experience: Works Locally, Crashes in Production – 80% Packaging or External Dependency Issues

The author has been bitten multiple times: IDE automatically adds all dependencies to the classpath during local runs, masking missing packaging configuration. At deploy time, misconfigured plugins leave dependencies out of the JAR. Another common pattern: shared JARs placed in /opt/libs on the server and loaded via -Dloader.path; forgetting to add that path in the startup script (or a typo) causes NoClassDefFoundError.

When encountering a class-not-found error, ask:

Is this a first-time deployment or an existing service suddenly failing? First deploy → likely packaging or startup script issue. Sudden failure → possibly deleted JAR or version upgrade conflict.

Is the error ClassNotFoundException or NoClassDefFoundError? Former → check dependencies; latter → check packaging/external paths.

Can you reproduce locally? Reproducible locally → missing dependency. Not reproducible → packaging or environment issue.

One-Sentence Summary: Class-not-found splits into two categories: missing dependencies → fix config; runtime errors → inspect packaging artifact and external dependency paths. Don't just stare at code—watch your JARs and startup scripts.

Five-Error Quick Reference Cheat Sheet

Null Pointer → Enable SQL logging, check if Total is 0, prioritize data self-check.

Connection Refused → Telnet test connectivity; if connected check config, else check service + firewall.

Timeout → Distinguish connect vs read timeout, treat accordingly, don't blame network blindly.

Primary Key Conflict → Disable manual primary key assignment, query before insert.

Class Not Found → Distinguish the two error types, then check dependencies, packaging artifact, external paths in order.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

debuggingDependency ManagementMavenSpring BootMySQLTroubleshootingNoClassDefFoundErrorClassNotFoundExceptionduplicate entryprimary key conflict
Engineer Tang's Implementation Study Notes
Written by

Engineer Tang's Implementation Study Notes

Old Tang | Pseudo-full-stack tech player: writes code without going bald, manages projects without going crazy, delivers without staying up late. No formal tutorials here, only a "slacking-off" practical manual that cures system pain points. Focuses on Shell, SQL, Java, and delivery, turning complexity into simplicity and making efficiency fun.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.