Home > database >  Cannot resolve symbol repository
Cannot resolve symbol repository

Time:10-17

I have a StudentRepository and a Student Config file but when I try to had a repository.saveAll function in the StudentConfig file, I get an error saying Cannot resolve symbol 'repository' . Am I missing an obvious annotation somewhere?

I'm following this tutorial which is good but it misses a few things which is annoying https://www.youtube.com/watch?v=9SGDpanrc8U

My Student repository file is like so:

package com.example.demo.student;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
}

My StudentConfig file is like so which contains the following error causer towards the bottom of the code block

repository.saveAll(
                        List.of(mariam, alex)
                )

: ->

package com.example.demo.student;

import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.LocalDate;
import java.time.Month;
import java.util.List;


@Configuration
public class Studentconfig {

    // we want this bean
    @Bean
    CommandLineRunner commandLineRunner() {
        return args -> {
            Student mariam = new Student(
                    "Mariam",
                    "[email protected]",
                    LocalDate.of(2000, Month.JANUARY, 5)
            );

            Student alex = new Student(
                    "Alex",
                    "[email protected]",
                    LocalDate.of(2004, Month.JANUARY, 5)
            );

            // invoke repository where we have the ability to save 1 student or list of all

            repository.saveAll(
                    List.of(mariam, alex)
            );
        };
    }
}

CodePudding user response:

To me it seems you are trying to do this:

@Component
public class ApplicationRunner implements CommandLineRunner{

    @Autowired
    private StudentRepository repository;
    
    @Override
    public void run(String... args) throws Exception {
        Student mariam = new Student(
                        "Mariam",
                        "[email protected]",
                        LocalDate.of(2000, Month.JANUARY, 5)
                );
        
        Student alex = new Student(
                "Alex",
                "[email protected]",
                LocalDate.of(2004, Month.JANUARY, 5)
        );
        
        repository.saveAll(
                List.of(mariam, alex)
        );
    }
}

Now your StudentRepository will get injected/autowired into your component and it will be available inside the run method.

  • Related