Search code examples
spring-bootentitymanagerspring-context

creating bean of a class in Spring Boot application?


I am trying to excess Entity Manager directly from Spring boot application. But I am unable to create bean of a class containing methods which I need. I am referring from the following article.

https://dzone.com/articles/accessing-the-entitymanager-from-spring-data-jpa

ProductCategoryRepositoryCustom Intraface:-

public interface ProductCategoryRepositoryCustom {

   public void merge(ProductCategory productcategory);
   public ProductCategory find(int id);
   public void persist(ProductCategory productcategory);

}

ProductCategoryRepositoryImpl implements ProductCategoryRepositoryCustom :-

@Component
public class ProductCategoryRepositoryImpl implements ProductCategoryRepositoryCustom {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public void merge(ProductCategory productcategory) {
        entityManager.merge(productcategory);
    }

    @Override
    public ProductCategory find(int id) {
        ProductCategory productCategory=entityManager.find(ProductCategory.class,id);
        return productCategory;
    }

    @Override
    public void persist(ProductCategory productcategory) {
          entityManager.persist(productcategory);
    }
}

Configuration Class:-

@Configuration
public class ProductConfig {
    
    @Bean
    public ProductCategoryRepositoryImpl productCategoryRepositoryImpl(){
        return new ProductCategoryRepositoryImpl();
    } 

}

After all these thing when I am trying to Auto-wire it with @Autowire annotation I am unable to access the methods which i have implemented.


Solution

  • You don't need a configuration class. Your Repository is a bean already due to @Component annotation.