[英]How can I do CRUD operations through CrudRepository in Spring?
I'm working with PostgresSQL and I have the following interface:我正在使用 PostgresSQL,我有以下界面:
@Repository
public interface ExampleRepository extends CrudRepository<ExampleEntity, Long> { }
Then I try to get the bean:然后我尝试获取 bean:
ExampleRepository repository = ctx.getBean(ExampleRepository.class);
Of course, I can't do that, because there's no implementation and eventually I get当然,我不能那样做,因为没有实现,最终我得到了
NoSuchBeanDefinitionException: No qualifying bean of type 'ExampleRepository'
I know this is a wrong approach, but since I'm not enough experienced, I've got no idea how I can communicate with my database.我知道这是一种错误的方法,但由于我经验不足,我不知道如何与我的数据库进行通信。 Any example I searched only explained how to implement services & controllers in order to interact with db through Browser.我搜索的任何示例仅解释了如何实现服务和控制器以便通过浏览器与数据库交互。 But I want to do CRUD operation inside the java code.但是我想在 java 代码里面做 CRUD 操作。
Could anyone explain it to me?谁能给我解释一下? Any related sources would also be fine.任何相关的来源也可以。
I am not sure how you are getting context (ctx) here.我不确定您是如何在此处获取上下文 (ctx) 的。 But the common approach is @Repository is not needed instead, @EnableJPARepositories should be used in the @Configuration file.但是通常的方法是不需要 @Repository,而是应该在 @Configuration 文件中使用 @EnableJPARepositories。 Then use @Autowired to inject the repository into your service class (where you want to execute operation from your repository bean) You can refer below link for more details https://mkyong.com/spring-boot/spring-boot-spring-data-jpa/然后使用@Autowired 将存储库注入您的服务 class(您要从存储库 bean 执行操作的位置)您可以参考以下链接了解更多详细信息https://mkyong.com/spring-boot/spring-boot-spring-数据-jpa/
You don't need to create bean.您不需要创建 bean。 It will created by the spring framework because you annotated your interface as @Repository
.You need only @Autowired
in your service class or where do you want to use this reference.它将由 spring 框架创建,因为您将接口注释为@Repository
。您只需要在服务 class 中使用@Autowired
或您想在哪里使用此引用。
@Autowired
private ExampleRepository exampleRepository;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.