简体   繁体   English

Java Spring JPA存储库

[英]Java Spring JPA Repository

I'm a Spring noob and I'm struggling with it. 我是Spring菜鸟,正在努力。

Basically before starting develop my Server with Spring in conjunction with JPA I tried to start a simple example just to get used to this framework. 基本上,在开始使用Spring和JPA一起开发Server之前,我试图开始一个简单的示例,以适应该框架。 I've already get succeded in make Spring working with some frameworks as Log4J, Swagger and others. 我已经成功使make Spring与某些框架一起使用,例如Log4J,Swagger等。 Now I'm trying to work with JPA and there are some points i can find out the solution. 现在,我正在尝试使用JPA,我可以从中找到一些解决方案。

I saw some blogs on how to develop with it and from all thousands options i choose to create my Repository Interfece and extend Repository<T, ID> . 我看到了一些有关如何使用它进行开发的博客,以及从我选择创建我的Repository Interfece并extend Repository<T, ID>所有成千上万个选项中的博客。 You can see my code bellow: 您可以在下面看到我的代码:

package com.example.model;
@Entity
public class Person {

    @Id
    public Integer id;

    public String name;

    public Person(){}
}

package com.example.repository;
public interface PersonRepository extends Repository<Person, Integer> {
    Collection<Person> findAll();
}


package com.example.controller;
@RestController
public class PersonController {

    @Autowired
    private PersonRepository repo;

    @RequestMapping(value = "/persons", method = RequestMethod.GET)
    public Collection<Person> getAll() {
        return repo.findAll();
    }
}

package com.example;
@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

And I also have the application.properties file: 我也有application.properties文件:

spring.datasource.platform=postgres
spring.datasource.url=jdbc:postgresql://localhost:5432/test_db
spring.datasource.username=test
spring.datasource.password=test
spring.datasource.driver-class-name=org.postgresql.Driver

When I put the server running I get the following exception: 当服务器运行时,出现以下异常:

: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.example.repository.PersonRepository com.example.controllers.PersonController.repo; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.example.repository.PersonRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: 
: Closing JPA EntityManagerFactory for persistence unit 'default'
: Stopping service Tomcat
: Application startup failed

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.example.repository.PersonRepository com.example.controllers.PersonController.repo; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.example.repository.PersonRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

I created a Github Repository to share the code here . 我创建了一个Github存储库以在此处共享代码。

Any clue about what am I doing wrong? 关于我在做什么错的任何线索吗?

Just annotate your interface with @Repository. 只需使用@Repository注释您的界面。 And if that doesnt work try adding @EnableJPARepositories to the main class. 如果那不起作用,请尝试将@EnableJPARepositories添加到主类。

First thing here is why you need to implements the base interface Repository as doing so, you will not have usual CRUD operations. 这里的第一件事是为什么您需要执行基本接口存储库 ,而不用执行通常的CRUD操作。 For such operations is better to implements CrudRepository . 对于此类操作,最好实现CrudRepository Since you implement CrudRepository no need to define a findAll() Method and many well known others you can find in doc mentioned. 由于您实现了CrudRepository,因此无需定义findAll()方法以及可以在文档中找到的许多其他知名方法。

Furthermore, when using @SpringBootApplication Spring boot use default values. 此外,当使用@SpringBootApplication Spring启动使用默认值。 If you see the @SpringBootApplication definition you will see that : 如果看到@SpringBootApplication 定义 ,则会看到:

Many Spring Boot developers always have their main class annotated with @Configuration, @EnableAutoConfiguration and @ComponentScan. 许多Spring Boot开发人员的主类始终带有@ Configuration,@ EnableAutoConfiguration和@ComponentScan注释。 Since these annotations are so frequently used together (especially if you follow the best practices above), Spring Boot provides a convenient @SpringBootApplication alternative. 由于这些批注经常一起使用(特别是如果您遵循上述最佳实践),因此Spring Boot提供了一种方便的@SpringBootApplication替代方案。

The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan with their default attributes: [...] @SpringBootApplication注释等效于使用@ Configuration,@ EnableAutoConfiguration和@ComponentScan及其默认属性:[...]

That means when using default values for ComponentScan your packages sturctures shloud be as following : 这意味着当使用ComponentScan的默认值时,您的程序包结构应如下所示:

  1. com.example.model -> your entities com.example.model->您的实体
  2. com.example.repositoriy -> your repositories com.example.repositoriy->您的存储库
  3. com.example.controller -> controllers com.example.controller->控制器
  4. com.example -> MainApplication class com.example-> MainApplication类

Here is an example for default project structure The main Application Class should be in higher level package then the others. 这是默认项目结构的示例。主应用程序类应位于其他应用程序的更高级别的程序包中。 Unless you have to specify packages location with @ComponentScan. 除非必须使用@ComponentScan指定软件包的位置。

As you are beginner with the framework. 正如您是该框架的初学者一样。 I suggest you to always see classes definitions in official documentation. 我建议您始终在官方文档中查看类定义。

UPDATE : 更新

Here is an example from one of my spring boot projects 这是我的一个春季靴子项目的例子

在此处输入图片说明

Also see this spring guide for JPA 另请参阅本JPA 春季指南

尝试将@Repository批注添加到PersonRepository中,这可能是找不到它的原因。

您需要使用@Respository注释PersonRepository接口,否则spring上下文将无法识别它或为其创建实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM