当前位置: 首页 > 知识库问答 >
问题:

Spring数据JPA-考虑在配置中定义一个名为“entityManagerFactory”的bean

董俊晖
2023-03-14

我正在Spring中开发一个应用程序,使用Tomcat、Mysql5、Java8。。。问题是,由于“required bean‘entityManagerFactory’not found”问题,我无法部署它。我与同事一起开发了这个项目,但他们可以完美地部署它,即使我在Spring工具套件中复制粘贴相同的项目。怎么可能呢?错误:

    2016-12-15 17:41:12.777  WARN 3676 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'controlador': Unsatisfied dependency expressed through field 'usuarioDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usuarioRepository': Cannot create inner bean '(inner bean)#59e43e8c' 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)#59e43e8c': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
2016-12-15 17:41:12.783  INFO 3676 --- [           main] o.apache.catalina.core.StandardService   : Stopping service Tomcat
2016-12-15 17:41:12.807  WARN 3676 --- [ost-startStop-1] o.a.c.loader.WebappClassLoaderBase       : The web application [ROOT] appears to have started a thread named [Abandoned connection cleanup thread] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:
2016-12-15 17:41:12.826  INFO 3676 --- [           main] utoConfigurationReportLoggingInitializer : 

Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2016-12-15 17:41:12.940 ERROR 3676 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

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

Description:

Field usuarioDao in es.uc3m.tiw.Controladores.Controlador required a bean named 'entityManagerFactory' that could not be found.


Action:

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

这是我的pom.xml

    <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>es.uc3m.tiw</groupId>
    <artifactId>Cliente</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

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

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.2.RELEASE</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-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

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

    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
    </dependency>


    </dependencies>

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


</project>

这是我的存储库

    package es.uc3m.tiw.Daos;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import es.uc3m.tiw.dominios.Usuario;

public interface UsuarioRepository  extends JpaRepository<Usuario, Long> {

    List<Usuario> findAll();

    Usuario findByNombre(String nombre);
}

这是我的控制器

package es.uc3m.tiw.Controladores;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import es.uc3m.tiw.Daos.AdministradorRepository;
import es.uc3m.tiw.Daos.UsuarioRepository;
import es.uc3m.tiw.dominios.Administrador;
import es.uc3m.tiw.dominios.Usuario;

@RestController
public class Controlador {

@Autowired
private UsuarioRepository usuarioDao;
private AdministradorRepository administradorDao;



    @RequestMapping(value="/registroUsuario", method = RequestMethod.POST)
    public @ResponseBody Usuario registrarUsuario(@RequestBody Usuario usuarioARegistrar){
    usuarioDao.save(usuarioARegistrar); //guardar, editar, borrar, findbyOne(Primary key) son métodos que vienen implementados ya en el CrudRepository
    return usuarioARegistrar;
    }

    @RequestMapping(value="/editarUsuario", method = RequestMethod.POST)
    public @ResponseBody Usuario editarUsuario(Usuario usuarioAEditar){
            usuarioAEditar.setNombre(usuarioAEditar.getNombre());
            usuarioAEditar.setApellidos(usuarioAEditar.getApellidos());
            usuarioAEditar.setCiudad(usuarioAEditar.getCiudad());
            usuarioAEditar.setEmail(usuarioAEditar.getEmail());
            usuarioAEditar.setPassword(usuarioAEditar.getPassword());
            usuarioDao.save(usuarioAEditar);            
    return usuarioAEditar;
    }

    @RequestMapping(value="/eliminarUsuario", method = RequestMethod.DELETE)
    public @ResponseBody Usuario eliminarUsuario(Usuario usuarioAEliminar){
    usuarioDao.delete(usuarioAEliminar);
    return usuarioAEliminar;
    }

    @RequestMapping(value="/validar" ,method = RequestMethod.POST)
    public  @ResponseBody Usuario loginUsuario(@RequestBody Usuario usuarioPendiente){
    Usuario usuarioLogeado = null;
    List <Usuario> usuarios = usuarioDao.findAll();
    usuarioLogeado = comprobarUsuario(usuarios, usuarioPendiente.getEmail(),usuarioPendiente.getPassword()); 
    return usuarioLogeado;
    }

    @RequestMapping(value="/verPerfilUsuario", method = RequestMethod.GET)
    public @ResponseBody Usuario verPerfilUsuario(Usuario usuarioAMostrar){
        usuarioAMostrar.getNombre();
        usuarioAMostrar.getApellidos();
        usuarioAMostrar.getCiudad();
        usuarioAMostrar.getEmail();
        usuarioAMostrar.getPassword();
    return usuarioAMostrar;
    }

    @RequestMapping(value="/loginAdministrador" ,method = RequestMethod.POST)
    public  @ResponseBody Administrador loginAdministrador(@RequestBody Administrador administradorPendiente){
        Administrador administradorLogeado = null;
        List <Administrador> administradores = administradorDao.findAll();
        administradorLogeado = comprobarAdministrador(administradores, administradorPendiente.getEmail(),administradorPendiente.getPassword());
        return administradorLogeado;
    }

    private Usuario comprobarUsuario( List<Usuario> usuarios, String email, String password) {
            Usuario u = null;
            for (Usuario usuario : usuarios) {
                    if (email.equals(usuario.getEmail()) && password.equals(usuario.getPassword())){
                            u = usuario;
                            break;
                            }
                    }
            return u;
        } 

    private Administrador comprobarAdministrador( List<Administrador> administradores, String email, String password) {
        Administrador ad = null;
        for (Administrador administrador : administradores) {
                if (email.equals(administrador.getEmail()) && password.equals(administrador.getPassword())){
                        ad = administrador;
                        //break;
                        }
                }
        return ad;
    }
}

应用属性

server.port=8010
spring.datasource.url=jdbc:mysql://localhost:3306/tiw
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.driver-class-name = com.mysql.jdbc.Driver

spring.jpa.hibernate.ddl-auto = update

实体

package es.uc3m.tiw.dominios;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="USUARIOS")
public class Usuario implements Serializable {

        private static final long serialVersionUID = 1L;

        @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private long id;
        @Column(length = 25)
        private String nombre;
        @Column(length = 25)
        private String apellidos;
        @Column(length = 25)
        private String ciudad;
        @Column(length = 25, nullable = false, unique = true)
        private String email;
        @Column(length = 25, nullable = false)
        private String password;


        public Usuario() {
        }

        public Usuario(long id, String nombre, String apellidos, String ciudad, String password, String email) {
            super();
            this.id = id;
            this.nombre = nombre;
            this.apellidos = apellidos;
            this.ciudad = ciudad;
            this.password = password;
            this.email = email;
        }

        public long getId() {
            return id;
        }
        public void setId(long id) {
            this.id = id;
        }       
        public String getNombre() {
            return nombre;
        }       
        public void setNombre(String nombre) {
            this.nombre = nombre;
        }       
        public String getApellidos() {
            return apellidos;
        }   
        public void setApellidos(String apellidos) {
            this.apellidos = apellidos;
        }       
        public String getCiudad() {
            return ciudad;
        }
        public void setCiudad(String ciudad) {
            this.ciudad = ciudad;
        }       
        public String getPassword() {
            return password;
        }       
        public void setPassword(String password) {
            this.password = password;
        }   
        public String getEmail() {
            return email;
        }   
        public void setEmail(String email) {
            this.email = email;
        }
}

这里是我的主

package es.uc3m.tiw;

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

@SpringBootApplication
public class ClienteSpringApplication {

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

共有3个答案

毕宇
2023-03-14

您缺少存储库配置,因为您必须使用存储库对其进行配置,

以下内容不正确,

public interface UsuarioRepository  extends JpaRepository<Usuario, Long> {

相反,它应该配置为存储库,如下所示,

@Repository
public interface UsuarioRepository  extends JpaRepository<Usuario, Long> {

这将使其成为一个被扫描的bean,并将其视为一个存储库,然后您的以下代码也应按预期工作,

@Autowired
private UsuarioRepository usuarioDao;
熊俊人
2023-03-14

我也有同样的问题。当我检查maven构建日志时,我意识到hibernate包有一个错误,它抱怨“无效的LOC头(错误的签名)”。我通过删除下的子目录解决了这个问题。m2\repository\org\hibernate\hibernate core并重新编译我的项目。

史逸春
2023-03-14

在我的例子中,我有错误的依赖关系:spring数据jpa。当我改为spring boot starter数据jpa时,它解决了这个问题。我不需要在Repository或EnableJpa等位置添加任何注释。

 类似资料:
  • 我从以下链接下载了示例代码:https://spring.io/guides/gs/accessing-data-mysql/我更改了应用程序。属性文件如下: 之后,我转到源文件夹并运行以下命令:mvn clean spring boot:run发生此错误: 请帮我解决这个问题

  • 尝试启动Spring Boot应用程序时,我收到以下错误: 注意:仅当我将自动连线注释置于IDeviceRepository IDeviceRepository上方时,才会发生此错误 。java类 我还没有让持久化到数据库-但是正在创建实体 这是项目的目录结构: com。美国广播公司。初始化。应用JAVA com.abc.controller.ontroller.java com。美国广播公司。服

  • 角色JAVA 任务JAVA 使用者JAVA RoleRepository.java TaskRepository。JAVA 用户库 登录注册应用程序。JAVA application.properties http://maven.apache.org/xsd/maven-4.0.0.xsd" 波姆。xml [错误]测试运行:1,失败:0,错误:1,跳过:0,耗时:2.941秒

  • 尝试运行我的Spring启动应用程序,我的编译器说;“_worldcom.example.hello字段回购。UserService需要一个名为entityManagerFactory的bean,但找不到。 注入点有以下注释:-@org.springframework.beans.factory.annotation.自动生成(必需=true)" Spring启动的新手,所以我不太确定为什么我的项

  • 我只是在学习如何通过spring上传文档。所以,在进行这项工作时,我面临着上述问题。由于有许多问题与同一个问题相关,我参考了它们并尝试了所有方法,但没有一个问题得到纠正。事先,我不需要为我的存储库接口添加@Repository,也不需要在我的应用程序类中添加@EnableJpaRepositories,因为我已经使用了正确的包序列。如需更多参考,请参阅https://dzone.com/artic

  • 感谢您的帮助! 我有一个spring boot应用程序要连接到couchbase,详细信息如下 > 存储库接口 控制器类 Couchbase配置 当我尝试启动应用程序时,它会抛出以下错误,我尝试在这里和外面搜索许多文章,但它们没有帮助 任何帮助都将不胜感激,否则情况似乎很好。