没有找到 EntityManager bean?

Posted

技术标签:

【中文标题】没有找到 EntityManager bean?【英文标题】:EntityManger bean not found? 【发布时间】:2018-05-04 19:35:53 【问题描述】:

ConfigServletWebServerApplicationContext :刷新 org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@769f71a9:启动日期 [Tue Nov 21 15:46:02 IST 2017];上下文层次的根 2017-11-21 15:46:24.774 INFO 6272 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer:Tomcat 使用端口初始化:8080 (http) 2017-11-21 15:46:24.922 INFO 6272 --- [main] o.apache.catalina.core.StandardService:启动服务 [Tomcat] 2017-11-21 15:46:24.924 INFO 6272 --- [main] org.apache.catalina.core.StandardEngine:启动 Servlet 引擎:Apache Tomcat/8.5.23 2017-11-21 15:46:25.250 INFO 6272 --- [ost-startStop-1] ocatalina.core.AprLifecycleListener:在 java 上找不到基于 APR 的 Apache Tomcat Native 库,它允许在生产环境中实现最佳性能。 library.path: [C:\Program Files\Java\jdk1.8.0_141\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\ProgramData\Oracle\ Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\110\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\120\Tools\Binn\;C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;C: \Program Files\Microsoft SQL Server\120\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\120\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\120\ Tools\Binn\ManagementStudio\;C:\Windows\system32\config\systemprofile.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\ ;C:\程序文件s (x86)\Windows Kits\8.1\Windows Performance Toolkit\;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0\;C :\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\PrivateAssemblies\;C:\Program Files\nodejs\;C:\Program Files\Java\jdk1.8.0_141\bin;C:\Users\kaleti \AppData\Local\Microsoft\WindowsApps;C:\Users\kaleti\AppData\Roaming\npm;C:\Users\kaleti\AppData\Local\GitHubDesktop\bin;.] 2017-11-21 15:46:25.628 INFO 6272 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]:初始化 Spring 嵌入式 WebApplicationContext 2017-11-21 15:46:25.629 INFO 6272 --- [ost-startStop-1] os.web.context.ContextLoader:根 WebApplicationContext:初始化在 23087 毫秒内完成 2017-11-21 15:46:25.986 INFO 6272 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean:映射 servlet:'dispatcherServlet' 到 [/] 2017-11-21 15:46:25.986 INFO 6272 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean:映射过滤器:'characterEncodingFilter' 到:[/] 2017-11-21 15:46:25.986 INFO 6272 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean:映射过滤器:'hiddenHttpMethodFilter' 到:[/] 2017-11-21 15:46:25.986 INFO 6272 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean:映射过滤器:“httpPutFormContentFilter”到:[/] 2017-11-21 15:46:25.986 INFO 6272 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean:映射过滤器:'requestContextFilter' 到:[/] 2017-11-21 15:46:26.625 WARN 6272 --- [main] ConfigServletWebServerApplicationContext:上下文初始化期间遇到异常-取消刷新尝试:org.springframework.beans.factory.UnsatisfiedDependencyException:创建名为“statusController”的bean时出错:不满意通过字段“statusService”表示的依赖关系;嵌套异常是 org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为“statusService”的 bean 时出错:通过字段“repository”表示的依赖关系不满足;嵌套异常是 org.springframework.beans.factory.BeanCreationException:创建名称为“repositoryImpl”的 bean 时出错:设置 bean 时无法创建类型为 [org.springframework.orm.jpa.SharedEntityManagerCreator] 的内部 bean '(inner bean)#340b7ef6'属性“实体管理器”;嵌套异常是 org.springframework.beans.factory.BeanCreationException:创建名称为 '(inner bean)#340b7ef6' 的 bean 时出错:设置构造函数参数时无法解析对 bean 'entityManagerFactory' 的引用;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available 2017-11-21 15:46:26.656 INFO 6272 --- [main] o.apache.catalina.core.StandardService:停止服务 [Tomcat] 2017-11-21 15:46:26.788 INFO 6272 --- [主] ConditionEvaluationReportLoggingListener:

启动 ApplicationContext 时出错。要显示条件报告,请在启用“调试”的情况下重新运行您的应用程序。 2017-11-21 15:46:26.983 错误 6272 --- [主] o.s.b.d.LoggingFailureAnalysisReporter 应用程序启动失败*********************************

说明: com.learning.demo.StatusService 中的字段存储库需要一个名为“entityManagerFactory”的 bean,但无法找到。 行动:

考虑在您的配置中定义一个名为“entityManagerFactory”的 bean。

进程以退出代码 1 结束

我的代码如下

package com.learing.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

    @SpringBootApplication
    public class DemoApplication 
        public static void main(String[] args) 
            SpringApplication.run(DemoApplication.class, args);
        
    

StatusController 类

package com.learing.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class StatusController 

@Autowired
private StatusService statusService;

@RequestMapping("/getEmpStatus")
public List<Employee> GetAllEmployeeStatus()
    return statusService.GetAllEmpStatus();


@RequestMapping("/getEmpStatus/id")
public Employee GetAllEmployeeStatus(@PathVariable int id)
    return statusService.GetEmpStatus(id);


@RequestMapping(method= RequestMethod.POST, value="/getEmpStatus")
 public void  AddEmployeeStatus(@RequestBody Employee employee)
    statusService.AddEmployeeStatus(employee);


@RequestMapping(method = RequestMethod.PUT, value="/getEmpStatus/id")
public void  UpdateStatus(@RequestBody Employee employee, @PathVariable int id)
     statusService.UpdateStatus(employee,id);

@RequestMapping(method= RequestMethod.DELETE, value="/getEmpStatus/id")
public void  UpdateStatus(@PathVariable int id)
    statusService.DeleteStatus(id);

状态服务类

    package com.learing.demo;

    import org.springframework.beans.factory.annotation.Autowired;

    import org.springframework.context.annotation.Bean;
    import org.springframework.stereotype.Service;

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;

    @Service
    public class StatusService 

        @Autowired
        public RepositoryImpl repository;

        private List<Employee> employees = new ArrayList<>(Arrays.asList(new Employee(1, "NSIN253", "Kalpa", "BHS-Mapping", "Mapping doc Completed"), new Employee(2, "NSIN254", "Fareeda", "BHS-Mapping", "Mapping doc Completed"), new Employee(3, "NSIN252", "KrishnaVeni", "BHS-Mapping", "Mapping doc Completed")));


        public List<Employee> GetAllEmpStatus() 
            return employees;
        

        public Employee GetEmpStatus(int id) 
            return employees.stream().filter(employee -> employee.getiD() == id).findFirst().get();
        

        public void AddEmployeeStatus(Employee employee) 
            repository.save(employee);
        

        public void UpdateStatus(Employee employee, int id) 
            for (int i = 0; i < employees.size(); i++) 
                Employee emp = employees.get(i);
                if (emp.getiD() == id) 
                    employees.set(i, employee);
                
            
        

        public void DeleteStatus(int id) 
            employees.removeIf(emp -> emp.getiD() == id);
        
    

RepositoryImpl 类

    package com.learing.demo;

    import org.springframework.data.repository.CrudRepository;
    import org.springframework.stereotype.Repository;

    @Repository
    public interface RepositoryImpl extends CrudRepository<Employee,Integer> 

    

应用道具:

spring.datasource.url=jdbc:sqlserver://localhost:1433;databaseName=EmployeeDb
    spring.datasource.username=xxxx
    spring.datasource.password=xxxxx
    spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
    spring.jpa.show-sql=true
    spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect
    spring.jpa.hibernate.ddl-auto =update

Pom.xml

<?xml version="1.0" encoding="UTF-8"?>

http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0

<groupId>com.learing</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>demo</name>
<description>Demo project for Spring Boot</description>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.BUILD-SNAPSHOT</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>com.microsoft.sqlserver</groupId>
        <artifactId>mssql-jdbc</artifactId>
        <scope>runtime</scope>

    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>4.1.4.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>5.2.3.Final</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>https://repo.spring.io/snapshot</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </repository>
</repositories>

<pluginRepositories>
    <pluginRepository>
        <id>spring-snapshots</id>
        <name>Spring Snapshots</name>
        <url>https://repo.spring.io/snapshot</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </pluginRepository>
    <pluginRepository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
        <snapshots>
            <enabled>false</enabled>
        </snapshots>
    </pluginRepository>
</pluginRepositories>

【问题讨论】:

你能显示正确的StatusController类吗,你显示的是错误的类 你现在可以检查一下我用状态控制器编辑的问题。 你为什么使用@Repository注解?如果你不处理一些特殊的数据访问异常,你可以省略它。见->javabeat.net/spring-annotations-component 好的,我从该类中删除了 Repository 注释。 【参考方案1】:

您需要从您的 POM 中删除这些:

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

【讨论】:

【参考方案2】:

Spring Data 使用名为 entityManagerFactory 的默认 bean 查找 EntityManagerFactory。

尝试在您的配置中使用以下注释,例如:

@EnableJpaRepositories(basePackages="com.learing.demo", entityManagerFactoryRef="en​​tityManagerFactory") 类配置

【讨论】:

【参考方案3】:

我在您的 application.properties 配置中发现了问题。你使用了错误的属性

改变。

spring.datasource.driverClassName=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect

spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.SQLServer2012Dialect

【讨论】:

是的,我修改了,但我仍然可以看到同样的问题。

以上是关于没有找到 EntityManager bean?的主要内容,如果未能解决你的问题,请参考以下文章

EntityManager方法简介

EntityManager执行原生sql结果集与bean的映射

Spring Boot-------JPA——EntityManager构建通用DAO

在条件下在无状态会话 Bean 中注入特定的 EntityManager

EntityManager bean 的 @Autowired 与 @PersistenceContext

Spring JPA/Hibernate EmptyInterceptor 不注入 Entitymanager/Spring bean