복붙노트

[SPRING] Spring-boot : 찾을 수없는 'entityManagerFactory'라는 이름의 bean이 필요합니다.

SPRING

Spring-boot : 찾을 수없는 'entityManagerFactory'라는 이름의 bean이 필요합니다.

JPA를 사용하고이 오류가 발생하는 스프링 부트 응용 프로그램을 개발 중입니다. 나는 정확한 주석이나 의존성이 없다면 확실하지 않습니다. 어떤 도움이라도 대단히 감사하겠습니다.

이것은 오류 메시지입니다.

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;
    }
}

해결법

  1. ==============================

    1."찾을 수없는 'entityManagerFactory'라는 bean이 필요합니다."라는 오류 메시지가 나타납니다.

    "찾을 수없는 'entityManagerFactory'라는 bean이 필요합니다."라는 오류 메시지가 나타납니다.

    인터넷 검색을 많이 한 후이 문제를 해결. JPA의 수동 구성을 설정했습니다.

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

    JPA는 기본적으로 세션을 검색합니다. 이름은 'entityManagerFactory' 그래서 내 코드를 다음과 같이 변경하십시오 :

    @Bean(name="entityManagerFactory")
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    
        return sessionFactory;
    } 
    
  2. ==============================

    2.당신은 exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}를 제거 할 필요가 있습니다 (이 경우 Spring은 자동으로 데이터 소스를 구성 할 것입니다). 또는 수동으로 데이터 소스를 설정하십시오

    당신은 exclude = {DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class}를 제거 할 필요가 있습니다 (이 경우 Spring은 자동으로 데이터 소스를 구성 할 것입니다). 또는 수동으로 데이터 소스를 설정하십시오

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

    업데이트 : 부동산에 실수가있는 것처럼 보입니다.

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

    첫 번째 줄에서 extra =를 제거하고 두 번째 줄에는 spring.datasource.driver-class-name 속성 이름을 사용하십시오.

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

    또한 MySQL 의존성에 버전을 추가하십시오 :

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

    나는 이러한 실수로 인해 Spring이 데이터 소스 유형을 올바르게 자동 감지 할 수 없다고 생각합니다.

  3. ==============================

    3.스프링 부트를 mysql 데이터베이스에 연결할 때 같은 문제가 발생합니다.

    스프링 부트를 mysql 데이터베이스에 연결할 때 같은 문제가 발생합니다.

    나를 구한 이유는 pom 파일에 hibernate-core의 올바른 버전을 추가하는 것이 었습니다. 최대 절전 모드부터 5.2.0. hibernate-entitymanager는 더 이상 필요하지 않습니다. Hibernate-core 5.2.0은 Spring Data JPA에 문제가있다. Spring Data JPA를 사용하고 있다면, process collection.Hibernate-core 5.2.1 이상은 Spring Data JPA에서 괜찮다.

    <dependency>
     <groupId>org.hibernate</groupId>
     <artifactId>hibernate-core</artifactId>
     <version> 5.2.1.Final</version>
    </dependency>
    
  4. ==============================

    4.EntityManagerFactory의 자동 생성을 우회하도록 선택했습니다. 따라서 Application 클래스의 구성 클래스 중 하나에 두 개의 bean을 folowing해야합니다.

    EntityManagerFactory의 자동 생성을 우회하도록 선택했습니다. 따라서 Application 클래스의 구성 클래스 중 하나에 두 개의 bean을 folowing해야합니다.

    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;
    }
    

    프로젝트에 최대 절전 모드 종속성을 추가하는 것을 잊지 마십시오.

  5. from https://stackoverflow.com/questions/48416927/spring-boot-required-a-bean-named-entitymanagerfactory-that-could-not-be-foun by cc-by-sa and MIT license