我有一個 StudentRepository 和一個 Student Config 檔案,但是當我嘗試repository.saveAll在 StudentConfig 檔案中使用一個函式時,我收到一條錯誤訊息Cannot resolve symbol 'repository'。我是否在某處遺漏了明顯的注釋?
我正在關注這個很好的教程,但它錯過了一些令人討厭的事情https://www.youtube.com/watch?v=9SGDpanrc8U
我的學生存盤庫檔案是這樣的:
包 com.example.demo.student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
}
我的 StudentConfig 檔案就像這樣,它在代碼塊的底部包含以下錯誤原因
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)
);
};
}
}
uj5u.com熱心網友回復:
對我來說,您似乎正在嘗試這樣做:
@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)
);
}
}
現在您StudentRepository將被注入/自動裝配到您的組件中,并且它將在 run 方法中可用。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/515363.html
標籤:爪哇弹簧靴jpa
