Alxa
Alxa

Reputation: 79

How can I do CRUD operations through CrudRepository in Spring?

I'm working with PostgresSQL and I have the following interface:

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

Then I try to get the 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.

Could anyone explain it to me? Any related sources would also be fine.

Upvotes: 0

Views: 236

Answers (2)

Saurabh Singh
Saurabh Singh

Reputation: 218

I am not sure how you are getting context (ctx) here. But the common approach is @Repository is not needed instead, @EnableJPARepositories should be used in the @Configuration file. 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/

Upvotes: 1

Jugal
Jugal

Reputation: 78

You don't need to create 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.

@Autowired 
private ExampleRepository exampleRepository;

Upvotes: 0

Related Questions