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;
}
Declaring a bean. To declare a bean, simply annotate a method with the @Bean annotation. When JavaConfig encounters such a method, it will execute that method and register the return value as a bean within a BeanFactory .
In the spring framework, @Component annotation marks a Java class as a bean so the component-scanning mechanism can find it and create its instance into the application context.
For each of the domain entities in the application, we define a repository interface with Spring Data. A repository includes all the methods such as sorting, paginating data and CRUD operations. For specifying that the underlying interface is a repository, a marker annotation @Repository is used.
Adding the following annotation in the main spring boot application class solved the issue in my case:
@ComponentScan("com.myapp.repositories")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With