/ Web Development

Save pre-defined data to the database in Spring Boot

Creator Image
Bashar Alshaibani
20 Sep 2024 -
1 min Reading time
@Component // This annotation tells Spring to treat this class as a component
public class CourseCategoryInitializer implements CommandLineRunner {
    @Autowired
    private CourseCategoryRepo courseCategoryRepository;

    @Override
    public void run(String... args) throws Exception {
        // Define a list of categories to be initialized
        List<String> categories = Arrays.asList("Agile", "Architecture", "Business Analysis", "Cyber Security", "Data", "Digital & Transformation",
                "IT Service Management", "Leadership & Personal Skill", "Project Management",
                "Microsoft", "Software Engineering", "Testing", "Requirements");

        // Loop through each category and save it if not already present
        for (String category : categories) {
            if (courseCategoryRepository.findByName(category).isEmpty()) {
                courseCategoryRepository.save(new CourseCategory(category));
            }
        }

        System.out.println("Course categories initialized.");
    }
}