### UserController Implementation (Java) Source: https://github.com/six-sprints/mongo-core/blob/main/README.md An example of a `UserController` that extends `AbstractCrudController` to handle RESTful API requests for User entities. ```java @RestController @RequestMapping("/api/users") public class UserController extends AbstractCrudController { public UserController(GenericCrudService service) { super(service); } } ``` -------------------------------- ### User Creation Test Source: https://github.com/six-sprints/mongo-core/blob/main/README.md A unit test example for creating a user using the UserService. It verifies that the created user has a non-null ID and slug. ```Java @SpringBootTest @ActiveProfiles("test") public class UserServiceTest extends BaseControllerTest { @Test public void testCreateUser() { User user = User.builder() .name("Test User") .email("test@example.com") .build(); User created = userService.insertOne(user); assertThat(created.getId()).isNotNull(); assertThat(created.getSlug()).isNotNull(); } } ``` -------------------------------- ### Basic Authentication Endpoint Source: https://github.com/six-sprints/mongo-core/blob/main/README.md Provides an example of a REST controller endpoint secured with basic authentication. The @BasicAuth annotation specifies the module and permission required to access the endpoint. ```Java @RestController public class UserController { @BasicAuth(module = BasicModuleEnum.USER, permission = BasicPermissionEnum.READ) @GetMapping("/profile") public ResponseEntity getProfile() { User currentUser = ApplicationContext.getCurrentUser(); return ResponseEntity.ok(currentUser); } } ``` -------------------------------- ### User Entity Definition (Java) Source: https://github.com/six-sprints/mongo-core/blob/main/README.md Example of extending the base entity `AbstractMongoEntity` to define a custom User entity with fields like name, email, and department. ```java @Data @EqualsAndHashCode(callSuper = true) @SuperBuilder @NoArgsConstructor @AllArgsConstructor @Document(collection = "users") public class User extends AbstractMongoEntity { private String name; private String email; private String department; // ... other fields } ``` -------------------------------- ### Custom Exception Handler Source: https://github.com/six-sprints/mongo-core/blob/main/README.md An example of a custom exception handler that intercepts specific exceptions (CustomException) and returns a custom ResponseEntity with an appropriate HTTP status. ```Java @ControllerAdvice public class CustomExceptionHandler extends RestExceptionHandler { @ExceptionHandler(CustomException.class) public ResponseEntity handleCustomException(CustomException ex) { return RestUtil.errorResponse(ex.getData(), ex.getMessage(), HttpStatus.BAD_REQUEST); } } ``` -------------------------------- ### Creating a User Entity Instance (Java) Source: https://github.com/six-sprints/mongo-core/blob/main/README.md Demonstrates how to create a new `User` object using the builder pattern and then save it using the `userService.insertOne()` method. ```java User newUser = User.builder() .name("John Doe") .email("john@example.com") .department("Engineering") .build(); User createdUser = userService.insertOne(newUser); ``` -------------------------------- ### UserService Implementation (Java) Source: https://github.com/six-sprints/mongo-core/blob/main/README.md Shows how to create a `UserService` by extending the generic `AbstractCrudService` for User entities, providing basic CRUD functionality. ```java @Service public class UserService extends AbstractCrudService { public UserService(GenericCrudRepository repository) { super(repository); } } ``` -------------------------------- ### Basic MongoDB Configuration (YAML) Source: https://github.com/six-sprints/mongo-core/blob/main/README.md Configuration for connecting to a MongoDB instance, specifying the connection URI and database name. ```yaml spring: data: mongodb: uri: mongodb://localhost:27017/your-database database: your-database ``` -------------------------------- ### Gradle Dependency for Mongo Core Source: https://github.com/six-sprints/mongo-core/blob/main/README.md This snippet demonstrates how to include the Mongo Core library in your project using Gradle. ```gradle implementation 'com.sixsprints:mongo-core:3.5.500' ``` -------------------------------- ### Custom Mongo Converters Configuration Source: https://github.com/six-sprints/mongo-core/blob/main/README.md Shows how to configure custom converters for MongoDB by extending a parent configuration class and adding custom converters to the list. ```Java @Configuration public class MongoConfig extends ParentMongoConfig { @Override protected List> converters() { List> converters = super.converters(); converters.add(new CustomConverter()); return converters; } } ``` -------------------------------- ### Exception Handling for Entity Not Found Source: https://github.com/six-sprints/mongo-core/blob/main/README.md Illustrates how the framework automatically converts exceptions, such as EntityNotFoundException, into appropriate HTTP responses (e.g., 404 Not Found). ```Java // Exceptions are automatically converted to HTTP responses try { User user = userService.findOneById(userId) .orElseThrow(() -> EntityNotFoundException.childBuilder() .error("User not found with ID: " + userId) .build()); } catch (EntityNotFoundException e) { // Automatically returns HTTP 404 with proper error message } ``` -------------------------------- ### Reading Entities by ID and Criteria Source: https://github.com/six-sprints/mongo-core/blob/main/README.md Demonstrates how to find entities by their unique ID and filter them using specific criteria. It utilizes Optional for single entity retrieval and Pageable for paginated results. ```Java // Find by ID Optional user = userService.findOneById("507f1f77bcf86cd799439011"); // Find with criteria Criteria criteria = Criteria.where(User.Fields.department).is("Engineering"); Page engineers = userService.filterByCriteria(criteria, PageRequest.of(0, 10)); ``` -------------------------------- ### Maven Dependency for Mongo Core Source: https://github.com/six-sprints/mongo-core/blob/main/README.md This snippet shows how to add the Mongo Core library as a Maven dependency to your Spring Boot project. ```xml com.sixsprints mongo-core 3.5.500 ``` -------------------------------- ### Custom Authentication Interceptor Source: https://github.com/six-sprints/mongo-core/blob/main/README.md Demonstrates how to implement a custom authentication interceptor by extending an abstract class. This allows for custom token handling and permission checking logic. ```Java @Component public class AuthInterceptor extends AbstractAuthenticationInterceptor { public AuthInterceptor(UserService userService) { super(userService); } @Override protected String authTokenKey() { return "X-AUTH-TOKEN"; } @Override protected void checkUserPermissions(User user, ModuleDefinition module, PermissionDefinition permission, boolean required) { // Custom permission logic } } ``` -------------------------------- ### Find All Entities (Java) Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/02-read-operations-basic.md Retrieves all entities as a list without pagination. Suitable for small datasets or when all entities are needed in memory. It takes no parameters and returns a List of entities. ```Java List allUsers = userCrudService.findAllList(); System.out.println("Total users: " + allUsers.size()); ``` -------------------------------- ### JWT Authentication Configuration (YAML) Source: https://github.com/six-sprints/mongo-core/blob/main/README.md YAML configuration for JWT authentication, including token expiry, shared secret, and issuer details. ```yaml # JWT Configuration token: expiry-in-days: 30 shared-secret: your-secret-key issuer: your-app-name ``` -------------------------------- ### Throw EntityNotFoundException in Java Service Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/10-exceptions.md Demonstrates how to throw a custom EntityNotFoundException from a Java service when a product is not found. It utilizes a builder pattern to set a custom error message. ```java import org.springframework.stereotype.Service; import lombok.RequiredArgsConstructor; import java.util.Optional; // Assuming Product and ProductCrudService are defined elsewhere // import com.sixsprints.core.exception.EntityNotFoundException; @Service @RequiredArgsConstructor public class ProductInventoryService { private final ProductCrudService productCrudService; public Product addInventory(String slug, Integer quantity) throws EntityNotFoundException { Optional product = productCrudService.findBySlugOptional(slug); if (product.isEmpty()) { throw EntityNotFoundException.childBuilder().error("Product not found with slug: " + slug).build(); } // ... rest of the code return null; // Placeholder } } ``` -------------------------------- ### Updating Entities with Patch Source: https://github.com/six-sprints/mongo-core/blob/main/README.md Illustrates how to perform a partial update (patch) on an entity by specifying the fields to be modified. It returns the updated entity. ```Java // Patch update User updateData = User.builder() .department("IT") .build(); User updatedUser = userService.patchUpdateOneById(userId, updateData, User.Fields.department); ``` -------------------------------- ### Pattern Matching Queries Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/02-read-operations-basic.md Filters entities based on a regular expression pattern applied to a specific field, such as matching email addresses. ```Java Criteria criteria = Criteria.where(User.Fields.email).regex(".*@company\\.com"); Page users = userCrudService.filterByCriteria(criteria); ``` -------------------------------- ### Deleting Entities Source: https://github.com/six-sprints/mongo-core/blob/main/README.md Shows how to delete single entities by their ID and perform bulk deletions based on specified criteria. Returns the count of deleted entities. ```Java // Single delete long deletedCount = userService.deleteOneById(userId); // Bulk delete Criteria criteria = Criteria.where(User.Fields.active).is(false); long deletedCount = userService.bulkDeleteByCriteria(criteria); ``` -------------------------------- ### Find Entities with Pagination (Java) Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/02-read-operations-basic.md Retrieves entities with pagination and sorting capabilities. It accepts a Pageable object for configuration and returns a Page object containing the results and metadata. Ideal for displaying entities in paginated lists or tables. ```Java Pageable pageable = PageRequest.of(0, 20, Sort.by(User.Fields.name).ascending()); Page userPage = userCrudService.findAll(pageable); System.out.println("Total users: " + userPage.getTotalElements()); System.out.println("Current page: " + userPage.getNumber()); System.out.println("Users on this page: " + userPage.getContent().size()); ``` -------------------------------- ### Perform Bulk Data Cleanup Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/04-delete-operations.md Performs bulk data cleanup by deleting old inactive users (inactive for over 5 years) and test users based on email patterns. ```Java public void performDataCleanup() { logger.info("Starting data cleanup process"); // Delete old inactive users Criteria oldInactiveCriteria = Criteria.where(User.Fields.active).is(false) .and(User.Fields.lastLogin).lt(LocalDateTime.now().minusYears(5)); long deletedCount = userCrudService.bulkDeleteByCriteria(oldInactiveCriteria); logger.info("Deleted " + deletedCount + " old inactive users"); // Delete test users Criteria testUserCriteria = Criteria.where(User.Fields.email).regex("test@.* "); deletedCount = userCrudService.bulkDeleteByCriteria(testUserCriteria); logger.info("Deleted " + deletedCount + " test users"); } ``` -------------------------------- ### Type-Safe Field References Source: https://github.com/six-sprints/mongo-core/blob/main/README.md Shows how to use type-safe field references, likely generated by Lombok's @FieldNameConstants, for querying and sorting entities. This improves code safety and maintainability. ```Java // Using Lombok @FieldNameConstants Criteria criteria = Criteria.where(User.Fields.department).is("Engineering"); Sort sort = Sort.by(User.Fields.name).ascending(); List fields = Arrays.asList(User.Fields.name, User.Fields.email); ``` -------------------------------- ### Bulk Insert Entities in Java Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/01-create-operations.md Inserts a list of new entities, with each entity undergoing validation and duplicate checks similar to `insertOne`. This operation is transactional, ensuring all or none are inserted. Returns the list of inserted entities. ```java List newUsers = Arrays.asList( User.builder() .name("Alice") .email("alice@example.com") .age(25) .build(), User.builder() .name("Bob") .email("bob@example.com") .age(30) .build() ); List createdUsers = userCrudService.bulkInsert(newUsers); System.out.println("Successfully created " + createdUsers.size() + " users."); ``` -------------------------------- ### Complex Sorting Configuration Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/02-read-operations-basic.md Applies complex sorting logic by defining multiple sort criteria, including ascending and descending order for different fields, and then applies this to a paginated query. ```Java Sort sort = Sort.by(User.Fields.department).ascending() .and(Sort.by(User.Fields.name).ascending()); Pageable pageable = PageRequest.of(0, 20, sort); Page users = userCrudService.findAll(pageable); ``` -------------------------------- ### Filter Entities with Pagination and Sorting Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/02-read-operations-basic.md Filters entities using MongoDB query criteria along with pagination and sorting configurations. This method is suitable for complex queries requiring specific data slicing and ordering. ```Java Criteria criteria = Criteria.where(User.Fields.age).gte(25).lte(50); Pageable pageable = PageRequest.of(0, 10, Sort.by(User.Fields.age).descending()); Page users = userCrudService.filterByCriteria(criteria, pageable); System.out.println("Found " + users.getTotalElements() + " users aged 25-50"); ``` -------------------------------- ### Bulk Migrate Department Users Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/03-update-operations.md Migrates users from one department to another by updating their department field. This method uses bulkPatchUpdateByCriteria to efficiently update multiple records based on a query. ```java public void migrateDepartment(String fromDept, String toDept) { Criteria criteria = Criteria.where("department").is(fromDept) .and("active").is(true); User updateData = User.builder() .department(toDept) .build(); List propsToUpdate = Arrays.asList(User.Fields.department); // Efficiently update all users in the department long updatedCount = userCrudService.bulkPatchUpdateByCriteria(criteria, updateData, propsToUpdate); System.out.println("Migrated " + updatedCount + " users from " + fromDept + " to " + toDept); } ``` -------------------------------- ### Update Operations in Mongo Core Source: https://github.com/six-sprints/mongo-core/blob/main/README.md Provides methods for updating documents in MongoDB. Supports full updates, partial updates (patch), and upsert operations, allowing updates by ID, slug, or custom criteria. Partial updates can specify changed properties. ```Java // Full update by ID updateOneById(String id, T entity) // Full update by slug updateOneBySlug(String slug, T entity) // Full update by criteria updateOneByCriteria(Criteria criteria, T entity) // Partial update by ID patchUpdateOneById(String id, T entity, String propChanged) patchUpdateOneById(String id, T entity, List propsChanged) // Bulk partial update by criteria bulkPatchUpdateByCriteria(Criteria criteria, T entity, String propChanged) bulkPatchUpdateByCriteria(Criteria criteria, T entity, List propsChanged) // Insert or update upsertOne(T entity) // Bulk insert or update bulkUpsert(List entities) ``` -------------------------------- ### Delete Operations in Mongo Core Source: https://github.com/six-sprints/mongo-core/blob/main/README.md Enables deletion of documents from MongoDB. Supports single and bulk deletions based on ID, slug, or custom criteria. Allows for efficient removal of multiple documents. ```Java // Delete by ID deleteOneById(String id) // Delete by slug deleteOneBySlug(String slug) // Delete by criteria deleteOneByCriteria(Criteria criteria) // Bulk delete by IDs bulkDeleteById(List ids) // Bulk delete by slugs bulkDeleteBySlug(List slugs) // Bulk delete by criteria bulkDeleteByCriteria(Criteria criteria) ``` -------------------------------- ### Find One Entity by Criteria (Java) Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/02-read-operations-basic.md Finds a single entity that matches the specified MongoDB criteria. It takes a Criteria object and returns an Optional containing the first matching entity. This is used for complex queries. ```Java Criteria criteria = Criteria.where(User.Fields.department).is("Engineering") .and(User.Fields.age).gte(25); Optional userOpt = userCrudService.findOneByCriteria(criteria); userOpt.ifPresent(user -> { System.out.println("Found engineer: " + user.getName()); }); // Alternative: Throw EntityNotFoundException if not found User user = userCrudService.findOneByCriteria(criteria) .orElseThrow(() -> EntityNotFoundException.childBuilder() .error("No engineer found matching criteria") .build()); ``` -------------------------------- ### Find User by Multiple Conditions Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/02-read-operations-basic.md Retrieves a single user entity that matches multiple specified criteria. This is useful for finding a unique record based on several attributes. ```Java Criteria criteria = Criteria.where(User.Fields.department).is("Engineering") .and(User.Fields.active).is(true) .and(User.Fields.age).gte(25); Optional userOpt = userCrudService.findOneByCriteria(criteria); ``` -------------------------------- ### Find One Entity by Slug (Java) Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/02-read-operations-basic.md Finds a single entity by its slug identifier. It accepts a slug string and returns an Optional containing the entity if found. This method is useful for retrieving entities using human-readable slug identifiers. ```Java String userSlug = "john-doe"; Optional userOpt = userCrudService.findOneBySlug(userSlug); userOpt.ifPresent(user -> { System.out.println("Found user by slug: " + user.getName()); }); // Alternative: Throw EntityNotFoundException if not found User user = userCrudService.findOneBySlug(userSlug) .orElseThrow(() -> EntityNotFoundException.childBuilder() .error("User not found with slug: " + userSlug) .build()); ``` -------------------------------- ### Filter Entities by Criteria (Java) Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/02-read-operations-basic.md Filters entities based on provided MongoDB criteria with default pagination. It accepts a Criteria object and returns a Page object containing the filtered entities. This is useful for filtered retrieval with default pagination settings. ```Java Criteria criteria = Criteria.where(User.Fields.active).is(true); Page activeUsers = userCrudService.filterByCriteria(criteria); System.out.println("Found " + activeUsers.getTotalElements() + " active users"); ``` -------------------------------- ### Insert One Entity in Java Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/01-create-operations.md Inserts a single new entity into the database after performing validation and duplicate checks. Returns the inserted entity with generated fields. Throws exceptions for invalid or duplicate entities. ```java User newUser = User.builder() .name("John Doe") .email("john@example.com") .age(30) .build(); User createdUser = userCrudService.insertOne(newUser); System.out.println("User created with ID: " + createdUser.getId()); ``` -------------------------------- ### Find One Entity by ID (Java) Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/02-read-operations-basic.md Finds a single entity by its unique identifier. It takes an ID string as input and returns an Optional containing the entity if found, or an empty Optional otherwise. This is useful for retrieving specific entities. ```Java String userId = "507f1f77bcf86cd799439011"; Optional userOpt = userCrudService.findOneById(userId); if (userOpt.isPresent()) { User user = userOpt.get(); System.out.println("Found user: " + user.getName()); } else { System.out.println("User not found"); } // Alternative: Throw EntityNotFoundException if not found User user = userCrudService.findOneById(userId) .orElseThrow(() -> EntityNotFoundException.childBuilder() .error("User not found with ID: " + userId) .build()); ``` -------------------------------- ### Range Queries for Entities Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/02-read-operations-basic.md Filters entities where a specific field falls within a given numerical range (greater than or equal to, and less than or equal to). ```Java Criteria criteria = Criteria.where(User.Fields.salary).gte(50000).lte(100000); Page users = userCrudService.filterByCriteria(criteria); ``` -------------------------------- ### Delete Users by Department Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/04-delete-operations.md Deletes users within a specified department. Supports both hard deletion and deletion by a list of user IDs for more control. ```Java public void deleteUsersByDepartment(String department, boolean forceDelete) { // Find users in the department Criteria deptCriteria = Criteria.where(User.Fields.department).is(department); Page usersInDept = userCrudService.filterByCriteria(deptCriteria); if (usersInDept.isEmpty()) { logger.info("No users found in department: " + department); return; } logger.info("Found " + usersInDept.getTotalElements() + " users in department: " + department); if (forceDelete) { // Hard delete all users in department long deletedCount = userCrudService.bulkDeleteByCriteria(deptCriteria); logger.info("Hard deleted " + deletedCount + " users in department: " + department); } else { // Delete by IDs for more control List userIds = usersInDept.getContent().stream() .map(User::getId) .collect(Collectors.toList()); long deletedCount = userCrudService.bulkDeleteById(userIds); logger.info("Deleted " + deletedCount + " users in department: " + department); } } ``` -------------------------------- ### Bulk Update User Status by Department Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/03-update-operations.md Updates the status of users within a specific department. It uses bulkPatchUpdateByCriteria to efficiently update records that do not already have the new status. ```java public void updateUserStatuses(String department, String newStatus) { Criteria criteria = Criteria.where("department").is(department) .and("status").ne(newStatus); User statusUpdate = User.builder() .status(newStatus) .build(); // Update status for all users in department who don't already have the new status long updatedCount = userCrudService.bulkPatchUpdateByCriteria(criteria, statusUpdate, User.Fields.status); System.out.println("Updated status to " + newStatus + " for " + updatedCount + " users in " + department); } ``` -------------------------------- ### Patch Update One Document by Criteria (Java) Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/03-update-operations.md Partially updates the first MongoDB document that matches the provided criteria. It takes the criteria, the entity with updated values, and a list of properties to change as input. It returns the updated entity or throws exceptions for not found or invalid entities. ```Java Criteria criteria = Criteria.where("department").is("Engineering") .and("level").is("JUNIOR"); User userUpdate = User.builder() .level("MID") .salary(60000) .updatedAt(LocalDateTime.now()) .build(); List propsToUpdate = Arrays.asList(User.Fields.level, User.Fields.salary, User.Fields.updatedAt); User updatedUser = userCrudService.patchUpdateOneByCriteria(criteria, userUpdate, propsToUpdate); System.out.println("Engineer promoted: " + updatedUser.getName()); ``` -------------------------------- ### Filter Entities with Custom Sorting Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/02-read-operations-basic.md Filters entities based on provided MongoDB query criteria and custom sorting configuration. It returns a paginated result set. ```Java Criteria criteria = Criteria.where(User.Fields.department).is("Engineering"); Sort sort = Sort.by(User.Fields.name).ascending(); Page engineers = userCrudService.filterByCriteria(criteria, sort); System.out.println("Engineers sorted by name: " + engineers.getContent().size()); ``` -------------------------------- ### Bulk Patch Update Multiple Properties by Criteria (Java) Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/03-update-operations.md Updates multiple specified properties for all MongoDB documents matching the given criteria. This is an efficient bulk operation. It returns the count of updated documents. ```Java Criteria criteria = Criteria.where("department").is("Legacy") .and("active").is(true); User updateData = User.builder() .department("Maintenance") .level("SENIOR") .updatedAt(LocalDateTime.now()) .build(); List propsToUpdate = Arrays.asList(User.Fields.department, User.Fields.level, User.Fields.updatedAt); long updatedCount = userCrudService.bulkPatchUpdateByCriteria(criteria, updateData, propsToUpdate); System.out.println("Migrated " + updatedCount + " users from Legacy to Maintenance department"); ``` -------------------------------- ### Bulk Delete Entities by IDs Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/04-delete-operations.md Efficiently deletes multiple entities by providing a list of their unique identifiers. The method returns the total count of deleted entities, which can range from 0 up to the size of the input list, and it ignores any non-existent IDs. ```Java List userIdsToDelete = Arrays.asList( "507f1f77bcf86cd799439011", "507f1f77bcf86cd799439012", "507f1f77bcf86cd799439013" ); long deletedCount = userCrudService.bulkDeleteById(userIdsToDelete); System.out.println("Deleted " + deletedCount + " out of " + userIdsToDelete.size() + " users"); ``` -------------------------------- ### Delete User Account Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/04-delete-operations.md Deletes a user account after verifying its existence and checking for active sessions or dependent data. Logs the deletion for auditing purposes. ```Java public ResponseEntity deleteUserAccount(String userId) { // Check if user exists first Optional userOpt = userCrudService.findOneById(userId); if (userOpt.isEmpty()) { return ResponseEntity.notFound().build(); } // Check for dependencies if (hasActiveSessions(userId) || hasDependentData(userId)) { return ResponseEntity.badRequest().body("Cannot delete user with active sessions or dependent data"); } // Perform deletion long deletedCount = userCrudService.deleteOneById(userId); if (deletedCount > 0) { auditService.logUserDeletion(userId, "Account deleted by admin"); return ResponseEntity.ok("User account deleted successfully"); } else { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body("Failed to delete user account"); } } ``` -------------------------------- ### Patch Update Multiple Properties by Slug Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/03-update-operations.md Partially updates multiple properties of an entity identified by its slug. It requires the entity's slug, the entity with new values, and a list of property names to update. Exceptions are thrown for entity not found or invalid entity. ```Java String userSlug = "john-doe"; User userUpdate = User.builder() .lastLogin(LocalDateTime.now()) .loginCount(15) .status("ONLINE") .build(); List propsToUpdate = Arrays.asList(User.Fields.lastLogin, User.Fields.loginCount, User.Fields.status); User updatedUser = userCrudService.patchUpdateOneBySlug(userSlug, userUpdate, propsToUpdate); System.out.println("User activity updated successfully"); ``` -------------------------------- ### Bulk Delete Entities by Criteria Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/04-delete-operations.md Permanently deletes all entities that match the specified MongoDB query criteria. The method returns the total number of deleted entities and completes without error if no entities satisfy the criteria. ```Java Criteria criteria = Criteria.where(User.Fields.active).is(false) .and(User.Fields.lastLogin).lt(LocalDateTime.now().minusYears(2)); long deletedCount = userCrudService.bulkDeleteByCriteria(criteria); System.out.println("Deleted " + deletedCount + " inactive users who haven't logged in for 2+ years"); ``` -------------------------------- ### Bulk Delete Entities by Slugs Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/04-delete-operations.md Removes multiple entities in bulk based on a list of their slug values. The operation returns the count of successfully deleted entities and gracefully handles slugs that do not correspond to any existing entities. ```Java List userSlugsToDelete = Arrays.asList( "john-doe", "jane-smith", "bob-johnson" ); long deletedCount = userCrudService.bulkDeleteBySlug(userSlugsToDelete); System.out.println("Deleted " + deletedCount + " out of " + userSlugsToDelete.size() + " users by slug"); ``` -------------------------------- ### Bulk Patch Update Single Property by Criteria (Java) Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/03-update-operations.md Updates a single specified property for all MongoDB documents matching the given criteria. This is an efficient bulk operation. It returns the count of updated documents. ```Java Criteria criteria = Criteria.where("department").is("Engineering") .and("level").is("JUNIOR"); User updateData = User.builder() .level("MID") .build(); long updatedCount = userCrudService.bulkPatchUpdateByCriteria(criteria, updateData, User.Fields.level); System.out.println("Promoted " + updatedCount + " junior engineers to mid-level"); ``` -------------------------------- ### Update User Profile by ID Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/03-update-operations.md Updates a user's profile using specific fields provided in the DTO. It utilizes the patchUpdateOneById method to efficiently update only the changed properties. ```java public ResponseEntity updateUserProfile(String userId, UserProfileUpdateDto profileUpdate) { User userUpdate = User.builder() .name(profileUpdate.getName()) .email(profileUpdate.getEmail()) .phone(profileUpdate.getPhone()) .build(); List changedProps = Arrays.asList(User.Fields.name, User.Fields.email, User.Fields.phone); User updatedUser = userCrudService.patchUpdateOneById(userId, userUpdate, changedProps); return ResponseEntity.ok(updatedUser); } ``` -------------------------------- ### Bulk Upsert Documents (Java) Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/03-update-operations.md Inserts or updates multiple MongoDB documents in a single transactional operation. If any entity in the batch fails validation, the entire operation is rolled back. It takes a list of entities and returns the list of successfully upserted entities. ```Java List users = Arrays.asList( User.builder() .name("Alice") .email("alice@example.com") .department("Engineering") .build(), User.builder() .name("Bob") .email("bob@example.com") .department("Marketing") .build() ); List upsertedUsers = userCrudService.bulkUpsert(users); System.out.println("Successfully upserted " + upsertedUsers.size() + " users"); ``` -------------------------------- ### Update Entity by Slug in Java Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/03-update-operations.md Updates an existing entity in MongoDB using its slug. This operation includes full validation and automatic audit field management. Exceptions are thrown for missing or invalid entities. ```Java String userSlug = "john-doe"; User updatedUser = User.builder() .name("John Smith") .email("john.smith@example.com") .build(); User result = userCrudService.updateOneBySlug(userSlug, updatedUser); System.out.println("User updated successfully: " + result.getName()); ``` -------------------------------- ### Update Entity by Criteria in Java Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/03-update-operations.md Updates the first entity in MongoDB that matches the provided criteria. This method enforces full validation and handles audit fields automatically. It can raise exceptions if no entity is found or if validation fails. ```Java Criteria criteria = Criteria.where("department").is("Engineering") .and("age").gte(25); User updatedUser = User.builder() .role("TEAM_LEAD") .salary(75000) .build(); User result = userCrudService.updateOneByCriteria(criteria, updatedUser); System.out.println("Updated engineer: " + result.getName()); ``` -------------------------------- ### Upsert One Document (Java) Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/03-update-operations.md Inserts a new MongoDB document if it does not exist, or updates an existing one based on its identifier. It takes the entity to upsert as input and returns the upserted entity. It can throw an exception if the entity fails validation. ```Java User user = User.builder() .name("John Doe") .email("john@example.com") .department("Engineering") .build(); User result = userCrudService.upsertOne(user); System.out.println("User upserted with ID: " + result.getId()); ``` -------------------------------- ### Delete Single Entity by Criteria Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/04-delete-operations.md Deletes the first entity that matches the provided MongoDB query criteria. It returns the count of deleted entities (0 or 1) and handles cases where no entities match the criteria silently. ```Java Criteria criteria = Criteria.where(User.Fields.department).is("Legacy") .and(User.Fields.active).is(false); long deletedCount = userCrudService.deleteOneByCriteria(criteria); if (deletedCount > 0) { System.out.println("First legacy user deleted successfully"); } else { System.out.println("No legacy users found to delete"); } ``` -------------------------------- ### Patch Update One Entity by Slug Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/03-update-operations.md Partially updates a single property of an entity identified by its slug. It requires the entity's slug, the entity with the new value, and the name of the property to update. Handles entity not found and invalid entity exceptions. ```Java String userSlug = "john-doe"; User userUpdate = User.builder() .status("ONLINE") .build(); User updatedUser = userCrudService.patchUpdateOneBySlug(userSlug, userUpdate, User.Fields.status); System.out.println("User status updated to: " + updatedUser.getStatus()); ``` -------------------------------- ### Patch Update One Entity by Criteria Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/03-update-operations.md Partially updates a single property of the first entity that matches the provided MongoDB criteria. It requires the criteria, the entity with the new value, and the name of the property to update. Handles entity not found and invalid entity exceptions. ```Java Criteria criteria = Criteria.where("department").is("Engineering") .and("role").is("JUNIOR"); User userUpdate = User.builder() .role("MID") .build(); User updatedUser = userCrudService.patchUpdateOneByCriteria(criteria, userUpdate, User.Fields.role); System.out.println("Promoted engineer: " + updatedUser.getName()); ``` -------------------------------- ### Patch Update One Entity by ID Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/03-update-operations.md Partially updates multiple properties of an entity identified by its unique ID. It requires the entity's ID, the entity with new values, and a list of changed property names. Throws exceptions for entity not found or invalid entity. ```Java String userId = "507f1f77bcf86cd799439011"; User userUpdate = User.builder() .department("Engineering") .role("TEAM_LEAD") .salary(75000) .build(); List changedProps = Arrays.asList(User.Fields.department, User.Fields.role, User.Fields.salary); User updatedUser = userCrudService.patchUpdateOneById(userId, userUpdate, changedProps); System.out.println("User updated:"); System.out.println("- Department: " + updatedUser.getDepartment()); System.out.println("- Role: " + updatedUser.getRole()); System.out.println("- Salary: " + updatedUser.getSalary()); ``` -------------------------------- ### Delete Single Entity by Slug Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/04-delete-operations.md Permanently deletes a single entity based on its slug field. The method returns the number of deleted entities (0 or 1) and proceeds without error if the entity is not found. ```Java String userSlug = "john-doe"; long deletedCount = userCrudService.deleteOneBySlug(userSlug); if (deletedCount > 0) { System.out.println("User with slug '" + userSlug + "' deleted successfully"); } else { System.out.println("User with slug '" + userSlug + "' not found"); } ``` -------------------------------- ### Delete Single Entity by ID Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/04-delete-operations.md Permanently deletes a single entity from the database using its unique identifier. It returns the count of deleted entities (0 or 1) and completes silently if the entity does not exist. ```Java String userId = "507f1f77bcf86cd799439011"; long deletedCount = userCrudService.deleteOneById(userId); if (deletedCount > 0) { System.out.println("User deleted successfully"); } else { System.out.println("User not found"); } ``` -------------------------------- ### Update Entity by ID in Java Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/03-update-operations.md Updates an existing entity in MongoDB by its unique identifier. This method performs full validation and automatically manages audit fields. It can throw exceptions for not found or invalid entities. ```Java String userId = "507f1f77bcf86cd799439011"; User updatedUser = User.builder() .name("John Smith") .email("john.smith@example.com") .department("Engineering") .role("SENIOR_DEVELOPER") .build(); User result = userCrudService.updateOneById(userId, updatedUser); System.out.println("User updated successfully: " + result.getName()); ``` -------------------------------- ### Partial Update Entity by ID in Java Source: https://github.com/six-sprints/mongo-core/blob/main/docs/generic-crud-service/03-update-operations.md Partially updates a single property of an entity in MongoDB by its ID. This method validates the entity and automatically updates audit fields. It throws exceptions for not found or invalid entities. ```Java String userId = "507f1f77bcf86cd799439011"; User userUpdate = User.builder() .department("IT") .build(); User updatedUser = userCrudService.patchUpdateOneById(userId, userUpdate, User.Fields.department); System.out.println("User department updated to: " + updatedUser.getDepartment()); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.