Consider defining a bean of type 'com.repository.UserRepository' in your configuration
Asked Answered
B

9

24

Hi I am doing JPA and Hibernate configuration using Java configuration in spring boot and I am stuck it at this error for hours. Even though I have declared the UserRepository as bean still it is not able to get the repository.

package com.repository;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {}

My service class which is using this repository:

package com.service;

@Service
public class AppointmentPaymentServiceImpl implements AppointmentPaymentService {

@Autowired
private UserRepository userRepository;
......
......
}

My Database configuration:

package com.config;

@Configuration
@PropertySource(value = { "classpath:application.properties" })
@EnableTransactionManagement
@EnableJpaRepositories("com.repository.*")
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class})
public class DBConfig {

@Value("${spring.datasource.driver-class-name}")
public String driver;

@Value("${spring.datasource.url}")
public String url;

@Value("${spring.datasource.username}")
public String username;

@Value("${spring.datasource.password}")
public String password;

@Value("${spring.jpa.properties.hibernate.dialect}")
public String dialect;

@Value("${spring.jpa.hibernate.ddl-auto}")
public String ddl;

@Bean(name = "dataSource")
public DriverManagerDataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(driver);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);

    return dataSource;
}


@Bean(name = "sessionFactory")
public LocalSessionFactoryBean hibernateSessionFactory(DataSource dataSource) {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(new String[] { "com.model.*" });
    sessionFactory.setHibernateProperties(hibernateProperties());
    return sessionFactory;
}


@Bean
HibernateTransactionManager transactionManagerHib(SessionFactory sessionFactory) {
    HibernateTransactionManager transactionManager = new HibernateTransactionManager();
    transactionManager.setSessionFactory(sessionFactory);
    return transactionManager;
}

/*@Bean
@Qualifier(value = "entityManager")
public EntityManager entityManager(EntityManagerFactory entityManagerFactory) {
    return entityManagerFactory.createEntityManager();
}*/

@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
    return new PersistenceExceptionTranslationPostProcessor();
}

@Bean
 public LocalContainerEntityManagerFactoryBean entityManagerFactory() {

HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
 vendorAdapter.setDatabase(Database.MYSQL);
 vendorAdapter.setGenerateDdl(true);

 LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
 em.setDataSource(dataSource());
 em.setPackagesToScan("com.model.*");
em.setJpaVendorAdapter(vendorAdapter);
 em.setJpaProperties(hibernateProperties());

 return em;
}

@Bean
 public PlatformTransactionManager transactionManager(EntityManagerFactory emf){
 JpaTransactionManager transactionManager = new JpaTransactionManager();
 transactionManager.setEntityManagerFactory(emf);

 return transactionManager;
}

Properties hibernateProperties() {
    return new Properties() {
        {
            setProperty("hibernate.hbm2ddl.auto", ddl);
            setProperty("hibernate.connection.useUnicode", "true");
            setProperty("spring.jpa.hibernate.ddl-auto", ddl);
            setProperty("hibernate.dialect", dialect);
            setProperty("spring.jpa.properties.hibernate.dialect", dialect);
            setProperty("hibernate.globally_quoted_identifiers", "true");
            setProperty("hibernate.connection.CharSet", "utf8mb4");
            setProperty("hibernate.connection.characterEncoding", "utf8");

        }
    };
}

}

And this is my main class:

package com; 

@SpringBootApplication
@ComponentScan(basePackages = { "com.*"})
@EnableCaching
@Configuration
@PropertySource({"classpath:logging.properties"})
public class MainApplication {

public static void main(String[] args) {
    SpringApplication.run(MainApplication.class, args);
}

}

My pom.xml contains these dependencies for hibernate and jpa if I use only spring data jpa then hibernate-core 5.0.12.Final is imported by default which I do not want:

  <dependencies>
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
    </dependency>
    .
    .
    .
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.10.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.2.3.Final</version>
    </dependency>
  </dependencies>

The error:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field userRepository in com.service.AppointmentPaymentServiceImpl required a bean of type 'com.repository.UserRepository' that could not be found.


Action:

Consider defining a bean of type 'com.repository.UserRepository' in your configuration.

My User Entity:

package com.model;

@Entity
@Table(name = "USER")
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
@Column(name = "id")
private Long id;

@NotNull
@Column(name = "city_id")
private Long cityId;

@Column(name = "name")
private String name;

@Column(name = "age")
private int age;

@Column(name = "locality")
private String locality;

@Column(name = "gender")
private String gender;

}
Beniamino answered 30/8, 2018 at 16:42 Comment(6)
Short answer: Don't use .* in your package spec.Vaucluse
yes I tried this way but it is then giving this error---> Caused by: java.lang.IllegalArgumentException: Not a managed type: class com..model.User @chrylisBeniamino
The '@Entity` annotation is the one from javax.... not the one from Hibernatate, right? (Not sure it still exists, but better check).Steib
You don't need @Repository on Spring Data Repositories.Steib
Add @Service annotation to your UserRepository interface.Garofalo
I am facing the same issue with Couchbase operations , @Service did not helpGaul
S
27

Adding the following annotation in the main spring boot application class solved the issue in my case:

@ComponentScan("com.myapp.repositories")

Schizogony answered 6/1, 2020 at 4:37 Comment(1)
Shouldn't the @Repositories be creating a Bean by default in Spring boot?Servomotor
N
13

Your @EnableJpaRepositories annotation is wrong. You don't define the package where the repositories are found this way.

Assuming that the package they reside is called:

foo.somepackage.repositories then you annotation should be @EnableJpaRepositories("foo.somepackage.repositories").

Try correcting the annotation in order to properly and correctly scan your repositories package in order to bring them into context.

Never answered 30/8, 2018 at 16:47 Comment(13)
yes I tried this way but it is then giving this error---> Caused by: java.lang.IllegalArgumentException: Not a managed type: class com..model.User @Aris_KortexBeniamino
actually scrap the last comment. the problem has to do with way you instruct the entity manager to scan packages. just lose .* in there and put the full package path.Never
Yes I have also tried this by removing .* from entityManagerFactory Bean gives this error-->Caused by: org.hibernate.MappingException: component property not found: idBeniamino
my user class is declared with @Entity annotation also and it does not contain any embedded object.Beniamino
I have also deleted the .m2 folder several times but still not working.Beniamino
@AyushSrivastava can you please share the User entity?Never
@Arix_Kortex I have updated my post along with user entity please check.Beniamino
I don't see why you need all that Configuration in the first place. The whole idea of spring boot is to avoid all thise boilerplate code and to not handroll the configuration unless you need to. Is there a reason you have done this and not just driven it through basic entity, Repository Interface, and propertiesDorettadorette
@AyushSrivastava do you have any other entities?Never
@Darren Forsythe ,I need this code because I am updating an old spring project which contains spring dispatcher and I need the hibernate SessionFactory bean.Beniamino
Yes @Aris_Kortex I have other entities also but for now I am getting component id not found error.Beniamino
@AyushSrivastava seems that some entity of yours is not declaring a pk correctly. The error you're getting seems to indicate so. Have a look at this #39040815Never
@Aris_Kortex yes I tried using the solution given in this thread but still the error persists.Beniamino
R
2

I think your code has to be organized under com.xyz.abc.model and the @EnableJpaRepostiories should work. eg: com.xyz.abc.repository, com.xyz.abc.service

Robomb answered 31/8, 2018 at 3:24 Comment(0)
B
2

It's because you are using Spring Data JPA.

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
</dependency>

Replace it with Spring Boot Starter Data JPA. It has all the necessary dependencies to fix the repository loading issue.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Bevel answered 4/10, 2023 at 17:7 Comment(0)
S
1

Just put AppointmentPaymentServiceImpl and UserRepository in the same package which for me was com.

Squiggle answered 18/10, 2020 at 20:21 Comment(0)
A
0

I had the same problem. I just copied the repositories from my working project to a new project and I got the same error consider defining a bean of type com.[packagename].repository.[repository-name]. Nothing above worked for me and later I did the following things:

  1. Removed the version of JPA dependancy in POM file (just removed the version tag)

  2. I was using Java 15 and when I created the SpringBoot project from start.spring.io, there was only 11 and 16 fava versions. So I selected 11 for my project. I changed that too in POM file

    15 (it was 11 before)
  3. Now I removed the @ComponentScan annotation in my main file, which was also a solution worked for me early.

  4. Just invalidate the cache and restart

  5. Type mvn clean install

  6. mvn clean spring-boot:run Hope this work for you too

Allocution answered 31/5, 2021 at 4:31 Comment(0)
U
0

Add any one of the following annotations to the main class of your spring boot application. Both of them worked for me.

@ComponentScan("com.abc.repository")
@EnableAutoConfiguration
Ungrateful answered 27/12, 2022 at 13:17 Comment(0)
A
0

In the @ComponentScan("") add your respective package in which your annotated class present

package com.graphql.springboot;

@SpringBootApplication
@ComponentScan("com.graphql.springboot.repo")
public class GraphqlSpringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(GraphqlSpringbootApplication.class, args);
    }

}

your service class

package com.graphql.springboot.serviceImpl;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    BookRepo bookRepo;

    @Override
    public List<Book> getAll() {
        return bookRepo.findAll();
    }

}

your repository class

package com.graphql.springboot.repo;

@Repository
public interface BookRepo extends JpaRepository<Book, Integer> {
}
Audry answered 3/1 at 19:21 Comment(0)
M
0

The Repository package needs to be inside the main .com file (Along with services and controller)

Mensal answered 16/2 at 11:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.