MergeUsersByUsernameDatabaseMigration implements ContextAwareTask { @Transactional @Override public void run(ApplicationContext applicationContext) throws TaskExecutionException { UserRepository userRepository = applicationContext.getBean(UserRepository.class); List<String> duplicatedUsernamesList = userRepository.findDuplicatedUsernamesCaseInsensitive(); Log.debug(Log.JEEVES, "Found these duplicated usernames: " + duplicatedUsernamesList); try { for (String duplicatedUsername : duplicatedUsernamesList) { mergeUsers(applicationContext, duplicatedUsername); } } catch (Exception e) { Log.error(Log.JEEVES, "Exception merging users", e); throw new TaskExecutionException(e); } }  @Transactional @Override void run(ApplicationContext applicationContext); User mergeUser(User toOverwrite, User toKeep);  }
@Test public void testRun() { User user1 = _userRepo.findOneByUsername("Username1"); User user2 = _userRepo.findOneByUsername("uSername1"); User user3 = _userRepo.findOneByUsername("usErname1"); User user4 = _userRepo.findOneByUsername("useRname1"); Group group1 = _groupRepo.findByName("groupTest1"); Group group2 = _groupRepo.findByName("groupTest2"); MergeUsersByUsernameDatabaseMigration migration = new MergeUsersByUsernameDatabaseMigration(); List<User> duplicatedUserNames = _userRepo.findByUsernameIgnoreCase("username1"); duplicatedUserNames.sort(Comparator.comparing(User::getProfile)); User greatestProfileUser = duplicatedUserNames.get(0); User userTmp = migration.mergeUser(new User(), greatestProfileUser); userTmp.setUsername(greatestProfileUser.getUsername().toLowerCase()); migration.run(_applicationContext); assertNull(_userRepo.findOne(user1.getId())); assertNull(_userRepo.findOne(user2.getId())); assertNull(_userRepo.findOne(user3.getId())); User mergedUser = _userRepo.findOne(greatestProfileUser.getId()); assertNotNull(mergedUser); assertEquals(userTmp.getUsername(), mergedUser.getUsername()); assertEquals(userTmp.getProfile(), mergedUser.getProfile()); assertEquals(userTmp.getPassword(), mergedUser.getPassword()); }