Spring Boot MongoDB中如何查找并处理重复条目?
Hey there! Since you're new to Spring Boot and looking to handle duplicate entries in MongoDB, let me break down exactly how to do this—from checking for duplicates to reporting them and creating new entries when it's safe.
First, let's create an entity class that maps to your MongoDB collection. We'll add indexes to entryName and barcode to speed up duplicate checks later (no need for unique constraints here since we want to handle the logic ourselves):
import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection = "entries") public class Entry { @Id private String id; @Indexed private String entryName; @Indexed private String barcode; // Constructor, getters, and setters public Entry(String entryName, String barcode) { this.entryName = entryName; this.barcode = barcode; } // Omit getters and setters for brevity—make sure to add them in your code! }
Use Spring Data MongoDB's repository to define a custom query method that checks for existing entries by name or barcode:
import org.springframework.data.mongodb.repository.MongoRepository; import java.util.Optional; public interface EntryRepository extends MongoRepository<Entry, String> { // Find any entry that matches either the given name OR barcode Optional<Entry> findByEntryNameOrBarcode(String entryName, String barcode); }
This is where the core logic lives—checking for duplicates, reporting them, and creating new entries when there's no match. For "reporting," I'll use a logger example, but you can adapt this to send alerts, save to a report table, or call an external API:
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @Service public class EntryService { private static final Logger logger = LoggerFactory.getLogger(EntryService.class); private final EntryRepository entryRepository; // Constructor injection (preferred over @Autowired) public EntryService(EntryRepository entryRepository) { this.entryRepository = entryRepository; } public String processEntryCreation(String entryName, String barcode) { // Check if a duplicate exists Optional<Entry> existingEntry = entryRepository.findByEntryNameOrBarcode(entryName, barcode); if (existingEntry.isPresent()) { // Report the duplicate Entry duplicate = existingEntry.get(); String reportMessage = String.format( "Duplicate entry alert: An entry with name '%s' or barcode '%s' already exists (ID: %s). New creation request rejected.", duplicate.getEntryName(), duplicate.getBarcode(), duplicate.getId() ); logger.warn(reportMessage); return reportMessage; } else { // No duplicates found—create and save the new entry Entry newEntry = new Entry(entryName, barcode); entryRepository.save(newEntry); return String.format("Entry created successfully! ID: %s", newEntry.getId()); } } }
If you want to expose this functionality via an HTTP API, add a simple controller:
import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class EntryController { private final EntryService entryService; public EntryController(EntryService entryService) { this.entryService = entryService; } @PostMapping("/entries") public ResponseEntity<String> createEntry( @RequestParam String entryName, @RequestParam String barcode ) { String result = entryService.processEntryCreation(entryName, barcode); if (result.contains("Duplicate entry alert")) { return ResponseEntity.badRequest().body(result); } return ResponseEntity.ok(result); } }
- Performance: The
@Indexedannotations onentryNameandbarcodeare crucial for speeding up duplicate checks as your database grows. - Concurrency Safety: If multiple requests might create duplicates at the same time, you could add a unique compound index on
entryNameandbarcodeat the database level, then catch the duplicate key exception in your service to handle reporting. - Custom Reporting: Replace the logger with your own reporting logic—like sending an email, saving to a
duplicate_reportscollection, or triggering a notification to your team.
内容的提问来源于stack exchange,提问作者JamieRhys

