我有一个 Spring Boot 应用程序,在其中创建了一个实体、一个存储库和一个服务。
我通过事务将实体保存在数据库中,一切正常,我的数据库已按我的预期填充。另外,我应该提到我的数据库是在 PHPMyAdmin 中创建的。
我还创建了一个存储库,以便通过扩展 Crud 存储库从数据库中获取一些数据。我还有一个服务存储调用存储库的方法。
但是,我的方法都没有返回任何内容(我的数据库不为空),我不知道为什么。我还尝试为实体添加 @EnableJpaRepositories 和 @ComponentScan,但这不起作用。以下是我的类(class):
实体(我不会把所有的 getter 和 setter 放在这里):
@Entity
@Table(name = "matches", schema = "tennis", catalog = "")
public class MatchesEntity {
private int id;
private String namePlayer1;
private String namePlayer2;
private int setsPlayer1;
private int setsPlayer2;
private String odd1;
private String odd2;
private String competition;
private String surface;
private String status;
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Basic
@Column(name = "Name_player1")
public String getNamePlayer1() {
return namePlayer1;
}
public void setNamePlayer1(String namePlayer1) {
this.namePlayer1 = namePlayer1;
}
@Basic
@Column(name = "Name_player2")
public String getNamePlayer2() {
return namePlayer2;
}
// other getter & setters
}
存储库:
@Repository
public interface MatchesRepository extends CrudRepository<MatchesEntity,
Integer> {
List<MatchesEntity> getAllBySurface(String surface);
}
服务:
@Service
public class MatchesService {
@Autowired
MatchesRepository matchesRepository;
public int countMatchesOnHard() {
return matchesRepository.getAllBySurface("hard").size();
}
public MatchesEntity findMatchById() {
return matchesRepository.findById(2378).get();
}
}
主类:
@SpringBootApplication
@EnableJpaRepositories(basePackageClasses={MatchesRepository.class})
@EntityScan(basePackageClasses=MatchesEntity.class)
public class PicksApplication {
@Autowired
static MatchesService matchesService;
public static void main(String[] args) {
MatchesEntity matchesEntity = matchesService.findMatchById();
int numberOfMatchesOnHard = matchesService.countMatchesOnHard();
System.out.println(numberOfMatchesOnHard);
}
}
我尝试的任何与存储库相关的方法都会返回 null。 谁能帮我提个建议吗?
最佳答案
你的主类PicksApplication
很麻烦。 main
方法必须触发 SpringApplication.run
以使 Spring Boot 初始化自身以及 Autowiring 工作的上下文。您正在破坏代码中的所有内容。您可以利用CommandLineRunner
并在 run()
方法中添加代码。
像这样;
@SpringBootApplication
public class PicksApplication implements CommandLineRunner {
@Autowired
private MatchesService matchesService;
public static void main(String[] args) {
SpringApplication.run(PicksApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
MatchesEntity matchesEntity = matchesService.findMatchById();
int numberOfMatchesOnHard = matchesService.countMatchesOnHard();
System.out.println(numberOfMatchesOnHard);
}
}
那么它应该可以工作,其余代码看起来没问题
关于java - 存储库相关方法仅返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58192733/