Spring-boot: required a bean named 'entityManagerFactory' that could not be found
Asked Answered
D

18

56

I am developing a Spring Boot application using JPA and encountering this error. I am not certain if I am using the correct annotations or missing dependencies. Any help would be greatly appreciated.

This is the error message

1:05:28 AM: Executing external task 'bootRun'...
:compileJava
:processResources UP-TO-DATE
:classes
:findMainClass
:bootRun
01:05:35.198 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Included patterns for restart : []
01:05:35.201 [main] DEBUG org.springframework.boot.devtools.settings.DevToolsSettings - Excluded patterns for restart : [/spring-boot-starter/target/classes/, /spring-boot-autoconfigure/target/classes/, /spring-boot-starter-[\w-]+/, /spring-boot/target/classes/, /spring-boot-actuator/target/classes/, /spring-boot-devtools/target/classes/]
01:05:35.201 [main] DEBUG org.springframework.boot.devtools.restart.ChangeableUrls - Matching URLs for reloading : [file:/C:/Users/zahid/IdeaProjects/giflib/build/classes/main/, file:/C:/Users/zahid/IdeaProjects/giflib/build/resources/main/]

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.3.RELEASE)

2018-01-24 01:05:35.539  INFO 14840 --- [  restartedMain] com.sweng.giflib.Application             : Starting Application on DESKTOP-EKFI3C8 with PID 14840 (C:\Users\zahid\IdeaProjects\giflib\build\classes\main started by zahid in C:\Users\zahid\IdeaProjects\giflib)
2018-01-24 01:05:35.540  INFO 14840 --- [  restartedMain] com.sweng.giflib.Application             : No active profile set, falling back to default profiles: default
2018-01-24 01:05:35.828  INFO 14840 --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@396ad740: startup date [Wed Jan 24 01:05:35 CST 2018]; root of context hierarchy
2018-01-24 01:05:37.685  INFO 14840 --- [  restartedMain] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2018-01-24 01:05:37.697  INFO 14840 --- [  restartedMain] o.apache.catalina.core.StandardService   : Starting service Tomcat
2018-01-24 01:05:37.699  INFO 14840 --- [  restartedMain] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.14
2018-01-24 01:05:37.800  INFO 14840 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-01-24 01:05:37.801  INFO 14840 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1976 ms
2018-01-24 01:05:37.991  INFO 14840 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2018-01-24 01:05:37.992  INFO 14840 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-01-24 01:05:37.992  INFO 14840 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-01-24 01:05:37.992  INFO 14840 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2018-01-24 01:05:37.993  INFO 14840 --- [ost-startStop-1] .s.DelegatingFilterProxyRegistrationBean : Mapping filter: 'springSecurityFilterChain' to: [/*]
2018-01-24 01:05:37.994  INFO 14840 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2018-01-24 01:05:38.291  WARN 14840 --- [  restartedMain] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'securityConfig': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userServiceImpl': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Cannot create inner bean '(inner bean)#64397422' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#64397422': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
2018-01-24 01:05:38.294  INFO 14840 --- [  restartedMain] o.apache.catalina.core.StandardService   : Stopping service Tomcat
2018-01-24 01:05:38.321  INFO 14840 --- [  restartedMain] utoConfigurationReportLoggingInitializer : 

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2018-01-24 01:05:38.444 ERROR 14840 --- [  restartedMain] o.s.b.d.LoggingFailureAnalysisReporter   : 

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

Description:

Field userRepository in com.sweng.giflib.service.UserServiceImpl required a bean named 'entityManagerFactory' that could not be found.


Action:

Consider defining a bean named 'entityManagerFactory' in your configuration.


BUILD SUCCESSFUL

Total time: 9.681 secs
1:05:38 AM: External task execution finished 'bootRun'.

build.gradle

buildscript {
    ext {
        springBootVersion = '1.5.3.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}


group 'com.sweng'
version '1.0-SNAPSHOT'


apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'

repositories {
    mavenCentral()
}

springBoot {
    mainClass = "com.sweng.giflib.Application"
}
dependencies {
    compile "org.springframework.boot:spring-boot-starter-data-jpa:$springBootVersion"
    compile "org.springframework.boot:spring-boot-starter-web:$springBootVersion"
    compile "org.springframework.boot:spring-boot-starter-thymeleaf:$springBootVersion"
    compile "org.springframework.boot:spring-boot-devtools:$springBootVersion"
    compile "mysql:mysql-connector-java"
    compile "org.springframework.boot:spring-boot-starter-security:$springBootVersion"
    compile "org.thymeleaf.extras:thymeleaf-extras-springsecurity4:2.1.2.RELEASE"

    providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
}

application.properties

spring.datasource.url== jdbc:mysql://localhost:3306/giflib
spring.db.driver= com.mysql.jdbc.Driver
spring.datasource.username = su
spring.datasource.password = 
spring.jpa.show-sql = true
#spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.naming.strategy = org.hibernate.cfg.ImprovedNamingStrategy

Application.java

package com.sweng.giflib;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@ComponentScan
@Configuration
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
@EnableJpaRepositories(basePackages = "com.sweng.giflib.repository")
@SpringBootApplication(scanBasePackages= "com.sweng.giflib")

public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

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

}

UserService.java

package com.sweng.giflib.service;

import com.sweng.giflib.model.User;
import org.springframework.security.core.userdetails.UserDetailsService;

public interface UserService extends UserDetailsService {
    User findByUsername(String username);
}

UserServiceImpl.java

package com.sweng.giflib.service;

import com.sweng.giflib.repository.UserRepository;
import com.sweng.giflib.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;

    @Override
    public User findByUsername(String username)
    {
        return userRepository.findByusername(username);
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // Load user from the database (throw exception if not found)
        User user = userRepository.findByusername(username);
        if(user == null) {
            throw new UsernameNotFoundException("User not found");
        }

        // Return user object
        return user;
    }

}

UserRepository.java

package com.sweng.giflib.repository;


import com.sweng.giflib.model.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends CrudRepository<User, Long>{
    User findByusername(String name);

}

User.java

package com.sweng.giflib.model;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import javax.persistence.*;
import javax.validation.constraints.Size;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Entity
public class User implements UserDetails {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true)
    @Size(min = 8, max = 20)
    private String username;

    @Column(length = 100)
    private String password;

    @Column(nullable = false)
    private boolean enabled;

    @OneToOne
    @JoinColumn(name = "role_id")
    private Role role;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(role.getName()));
        return authorities;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }
}
Diazotize answered 24/1, 2018 at 7:23 Comment(6)
why do you exclude DataSourceAutoConfiguration.class and HibernateJpaAutoConfiguration.class?Buyer
If I take out the exclude and simply have @EnableAutoConfiguration, Springboot throws an error about being unable to configure an inMemoryDatabase. This is what I see: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'inMemoryDatabaseShutdownExecutor' defined in class path resource [org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.class]: Error creating bean with name 'dataSource' defined in class path resourceDiazotize
try to start your app without any annotaion on your main class. Just leave @SpringBootApplication. Also without scanBasePackages= "com.sweng.giflib"Buyer
Thank you for the suggestion but with just the @SpringBootApplication and no other annotation I still get something about the inMemoryDatabasesShutdown. I see org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'inMemoryDatabaseShutdownExecutor' defined in class path resource [org/springframework/boot/devtools/autoconfigure/DevToolsDataSourceAutoConfiguration.class]: Unsatisfied dependency expressed through method 'inMemoryDatabaseShutdownExecutor' parameter 0;Diazotize
I've just noticed that you have some mistakes in your properties. Check my updated answerUltramodern
This post helped me fix the above problem SO postBeatriz
F
59

I was getting error message like-

required a bean named 'entityManagerFactory' that could not be found.

After lot of googling solve this problem. I set manual configuration for JPA.

@Bean 
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); 

    return sessionFactory;
}

but JPA by default search sessionFactory by name 'entityManagerFactory' so change my code as:

@Bean(name="entityManagerFactory")
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();

    return sessionFactory;
} 
Frierson answered 13/2, 2019 at 5:19 Comment(6)
So the bean has to be named "entityManagerFactory".................gaaaaaaaaaaaaaaaaaa more spring voodoo. :(Irritating
In my case I´m running into this problem using two datasources. One defined with the default properties and the other prgrammatically, by creating LocalContainerEntityManagerFactoryBean and PlatformTransactionManager beansExcurrent
Alternatively you can inform Spring Boot that your bean is named differently by: @EnableJpaRepositories(basePackages = "com.sweng.giflib.repository", entityManagerFactoryRef = "sessionFactory")Flinch
Thanks ! saved the day. Spring configuration through properties file automatically loads up sessionFactory as entityManagerFactory, problem comes when I am creating the beans manually.Elwaine
My SpringBoot 2.6 app didn't need @Bean(name="entityManagerFactory") name but when I migrated to SpringBoot 3, It did. Thanks!Alienor
Actually, if you have two datasource beans, the "required a bean named 'entityManagerFactory' that could not be found. " error also appearsBerndt
E
30

For me, I've forgotten to remove DataSourceAutoConfiguration.class from exclusions.

So this:

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
// Main class definition

Should be:

@SpringBootApplication()
// Main class definition
Euphrosyne answered 1/3, 2020 at 10:14 Comment(1)
Mine was this one, someone added before this. ThanksCymric
B
16

Run into same issue when trying to connect spring boot to mysql database.

What saved me was adding correct version of hibernate-core to my pom file. From hibernate onwards 5.2.0. hibernate-entitymanager is no longer needed. Hibernate-core 5.2.0 have problem with Spring Data JPA while process collection.Hibernate-core 5.2.1 and above is ok with Spring Data JPA if you are using Spring Data JPA.

<dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-core</artifactId>
 <version> 5.2.1.Final</version>
</dependency>
Booted answered 26/8, 2018 at 15:30 Comment(1)
For me, I needed to add hibernate dependencies that were missing in my pom (very similar to user9347049 's situationManno
C
6

in our case was working fine but not for tests with @WebMvcTest

Took a while to find out but issue was:

@SpringBootApplication
@ComponentScan({"com.givenproject"})
@EntityScan("com.givenproject")
@EnableJpaRepositories("com.givenproject")
@Configuration
public class Application {

instead do:

@SpringBootApplication
@Configuration
public class Application {

and

@Configuration
@ComponentScan({"com.givenproject"})
@EntityScan(basePackages = "com.givenproject")
@EnableJpaRepositories(basePackages = "com.givenproject")
public class DataConfig {
}
Complacency answered 8/2, 2021 at 11:43 Comment(0)
U
4

You either need to remove exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class} (and let Spring automatically configure your datasource) or configure your datasource manually

@Bean
@ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource() {
    return new YourCustomDataSource();
}

UPDATE: Seems like you have some mistakes in your properties:

spring.datasource.url== jdbc:mysql://localhost:3306/giflib
spring.db.driver= com.mysql.jdbc.Driver

Try to remove the extra = from the first line and use spring.datasource.driver-class-name property name for the second:

spring.datasource.url=jdbc:mysql://localhost:3306/giflib
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

Also add a version to your MySQL dependency:

compile "mysql:mysql-connector-java:6.0.6"

I think that because of these mistakes Spring is unable to autodetect your datasource type correctly.

Ultramodern answered 24/1, 2018 at 7:40 Comment(1)
Along with your response, I had to make another change since I was using 2 datasources (connecting to 2 different DBs). @Transactional(propagation = Propagation.REQUIRES_NEW, transactionManager = "yourCustomTransactionManagerBean") This will save few development days worth of efforts! Thanks for your answer, upvoted :)Dysplasia
T
4

I had same issue when have two custom data sources with flyway DB migration. After adding @primary annotation for one data source, it worked.

Tewell answered 15/3, 2023 at 14:1 Comment(0)
M
3

I was getting the issue , because I forgot to remove the annotation @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class }) that I had added, while testing hardcoded values. Resolved the issue by simply using @SpringBootApplication

Monteria answered 8/2, 2021 at 4:59 Comment(0)
A
2

You have chosen to bypass auto creation of EntityManagerFactory. Therefore you should add folowing two beans in one of your configuration classes, possibly in Application class.

private static String PROP_DB_DRIVER_CLASS = "spring.db.driver";
private static String PROP_DB_URL = "spring.datasource.url";
private static String PROP_DB_USER = "spring.datasource.username";
private static String PROP_DB_PASS = "spring.datasource.password";

@Autowired
private Environment env;

@Bean
public DataSource dataSource(){
      DriverManagerDataSource dataSource = new DriverManagerDataSource();
      dataSource.setDriverClassName(env.getProperty(PROP_DB_DRIVER_CLASS));
      dataSource.setUrl(env.getProperty(PROP_DB_URL));
      dataSource.setUsername(env.getProperty(PROP_DB_USER));
      dataSource.setPassword(env.getProperty(PROP_DB_PASS));
      return dataSource;
}

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
      LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
      em.setDataSource(dataSource());
      em.setPackagesToScan("com.sweng.giflib.model");

      JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
      em.setJpaVendorAdapter(vendorAdapter);
      em.setJpaProperties(additionalProperties());

      return em;
}

Don't forget to add the hibernate dependency to your project.

Adhamh answered 24/1, 2018 at 8:26 Comment(0)
A
1

Please rebuild your project and download all dependencies once again.I also face same issue and my issue was resolved by just downloading dependencies once

Alternately answered 15/10, 2022 at 5:53 Comment(0)
M
0

In my case the problem was exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class} declared in @SpringBootApplication annotation, so thanks to Kirill Simonov tip I solved the problem that spent all day long of searching and broking head. Removing it worked extremely fine for me after hours trying. Everything else was ok, @Service, @Autowired, @EnableAutoConfiguration and @ComponentScan are redundant in this spring boot version, so really much time trying tips in the internet.

I'm using spring boot 2.1.11.RELEASE version.

Programming is something funny, once I used the exclude solution to solve an error message, then the same thing was the problem now. So there's no magic spell or formula as this universe has lots and lots of different scenarios, even if it's similar to a previous one we worked on.

Motorcade answered 2/1, 2020 at 20:1 Comment(0)
H
0

In my case, I removed the version of mysql connector and let spring boot handle it. And it worked.

Hath answered 22/4, 2021 at 13:35 Comment(0)
C
0

Solved a problem by removing jooq dependency:

implementation("org.springframework.boot:spring-boot-starter-jooq")
Cinchonidine answered 29/9, 2021 at 21:7 Comment(2)
Is that a line you removed, or added?Supra
removed the dependencyCinchonidine
L
0

For me, I'm wrting Spring Unit Test, in the Cotroller I declare repository variable, I move the repository and its behavior to another new class, and called the new class method in Controller.

Besides, for the Application class in src\main which is same package with src\test, keep the Application simple like:

package yourpackage;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ApplicationTest {

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

}

then the problem is solved.

Loreeloreen answered 5/10, 2022 at 6:24 Comment(0)
H
0

Solved it by adding the missing annotation '@Entity'.

Howerton answered 9/11, 2022 at 12:7 Comment(0)
E
0

also I am facing same issue, because I forgot to mention jdbc before mysql://localhost:0000/databaseName .After adding correct mysql url path my issue is resolved.

Ermelindaermengarde answered 6/6, 2023 at 5:57 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Denysedenzil
D
0

I found the problem in my import the thing is that framework.data.annotation.id was the problem when I changed it with import javax.persistence.Id. It solved it (I am using 2.7 spring boot with java 11 ). I hope i could fix your problem.

Dejected answered 9/8, 2023 at 12:22 Comment(0)
S
0

Try checking version of H2 along with JPA. In my case there was issue with this version only.

Salicin answered 13/4 at 13:8 Comment(1)
Are you referring to this H2? Also, which version are you referring to? Which version works and which does not?Runway
M
-1

I tried several ways besides of mentioned suggestions to remove this error.I got resolved this error by just removing following code from application.properties

spring.jpa.properties.hibernate.cache.use_second_level_cache=true                                                   
spring.jpa.properties.hibernate.cache.use_query_cache=false                                                         
spring.jpa.properties.hibernate.generate_statistics=false                                                           
spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory
Matteo answered 26/12, 2019 at 13:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.