Initializing the MongoDB database

With the JPA implementation, we used the data.sql file to initialize the data in our database. For MongoDB implementation, we can remove the data.sql file and replace it with a Java configuration file, which we will call MongoDataInitializer.java:

    //src/main/java/com/packtpub/springsecurity/configuration/
MongoDataInitializer.java


@Configuration
public class MongoDataInitializer {
@Autowired
private RoleRepository roleRepository;
@Autowired
private CalendarUserRepository calendarUserRepository;
@Autowired
private EventRepository eventRepository;
@PostConstruct
public void setUp() {
calendarUserRepository.deleteAll();
roleRepository.deleteAll();
eventRepository.deleteAll();
seedRoles();
seedCalendarUsers();
seedEvents();
}
CalendarUser user1, admin, user2;
{
user1 = new CalendarUser(0, "user1@example.com",
"$2a$04$qr7RWyqOnWWC1nwotUW1nOe1RD5.mKJVHK16WZy6v49pymu1WDHmi",
"User","1");
admin = new CalendarUser(1,"admin1@example.com",
"$2a$04$0CF/Gsquxlel3fWq5Ic/ZOGDCaXbMfXYiXsviTNMQofWRXhvJH3IK",
"Admin","1");
user2 = new CalendarUser(2,"user2@example.com",
"$2a$04$PiVhNPAxunf0Q4IMbVeNIuH4M4ecySWHihyrclxW..PLArjLbg8CC",
"User2","2");
}
Role user_role, admin_role;
private void seedRoles(){
user_role = new Role(0, "ROLE_USER");
admin_role = new Role(1, "ROLE_ADMIN");
user_role = roleRepository.save(user_role);
admin_role = roleRepository.save(admin_role);
}
private void seedEvents(){
// Event 1
Event event1 = new Event(100, "Birthday Party", "This is
going to be a great birthday", new
GregorianCalendar(2017,6,3,6,36,00), user, admin);
// Event 2
Event event2 = new Event(101, "Conference Call",
"Call with the client",new
GregorianCalendar(2017,11,23,13,00,00),user2, user);
// Event 3
Event event3 = new Event(102, "Vacation",
"Paragliding in Greece",new GregorianCalendar(2017,8,14,11,30,00),
admin, user2);
// Save Events
eventRepository.save(event1);
eventRepository.save(event2);
eventRepository.save(event3);
}
private void seedCalendarUsers(){
// user1
user1.addRole(user_role);
// admin2
admin.addRole(user_role);
admin.addRole(admin_role);
// user2
user2.addRole(user_role);
calendarUserRepository.save(user1);
calendarUserRepository.save(admin);
calendarUserRepository.save(user2);
}
}

This will be executed at load time and will seed the same data into our MongoDB as we did with our H2 database.