【问题标题】:How can I do CRUD operations through CrudRepository in Spring?Spring 如何通过 CrudRepository 进行 CRUD 操作?
【发布时间】:2021-01-29 11:30:42
【问题描述】:

我正在使用 PostgresSQL,我有以下界面:

@Repository
public interface ExampleRepository extends CrudRepository<ExampleEntity, Long> { }

然后我尝试获取 bean:

ExampleRepository repository = ctx.getBean(ExampleRepository.class);

当然,我不能这样做,因为没有实现,最终我得到了

NoSuchBeanDefinitionException: No qualifying bean of type 'ExampleRepository'

我知道这是一种错误的方法,但由于我经验不足,我不知道如何与我的数据库进行通信。我搜索的任何示例都只解释了如何实现服务和控制器以便通过浏览器与数据库交互。但是我想在java代码里面做CRUD操作。

谁能给我解释一下?任何相关来源也可以。

【问题讨论】:

    标签: java spring jpa repository crud


    【解决方案1】:

    我不确定您是如何在此处获取上下文 (ctx) 的。 但是常用的方法是不需要@Repository,而是应该在@Configuration 文件中使用@EnableJPARepositories。然后使用 @Autowired 将存储库注入您的服务类(您希望从存储库 bean 执行操作的位置) 您可以参考以下链接了解更多详情 https://mkyong.com/spring-boot/spring-boot-spring-data-jpa/

    【讨论】:

      【解决方案2】:

      您不需要创建 bean。它将由 spring 框架创建,因为您将接口注释为 @Repository 。您只需要在您的服务类中使用 @Autowired 或您想在哪里使用此引用。

      @Autowired 
      private ExampleRepository exampleRepository;
      

      【讨论】:

      • 很遗憾,效果为零
      猜你喜欢
      • 2014-11-23
      • 2017-03-17
      • 1970-01-01
      • 1970-01-01
      • 2019-06-27
      • 2019-05-20
      • 1970-01-01
      • 2023-02-05
      • 1970-01-01
      相关资源
      最近更新 更多