Spring Data JPA - 考虑在您的配置中定义一个名为“entityManagerFactory”的bean
Posted
技术标签:
【中文标题】Spring Data JPA - 考虑在您的配置中定义一个名为“entityManagerFactory”的bean【英文标题】:Spring Data JPA - Consider defining a bean named 'entityManagerFactory' in your configuration 【发布时间】:2017-05-01 10:32:59 【问题描述】:我正在使用 Tomcat、mysql5、Java8 在 Spring 中开发应用程序...问题是我无法部署它,因为“找不到所需的 bean 'entityManagerFactory'”问题。我和我的同事一起开发了这个项目,但他们可以完美地部署它,解决任何问题,即使我在 Spring Tool Suite 中复制粘贴同一个项目。怎么可能? 错误:
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;
Application.properties
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);
【问题讨论】:
使用 main 方法的类看起来如何?是用@SpringBootApplication
注解的吗?它是否在任何其他人的根包中?
包 es.uc3m.tiw;导入 org.springframework.boot.SpringApplication;导入 org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication 公共类 ClienteSpringApplication public static void main(String[] args) SpringApplication.run(ClienteSpringApplication.class, args);
【参考方案1】:
就我而言,我有错误的依赖:spring-data-jpa。 当我更改为 spring-boot-starter-data-jpa 时,它解决了问题。 我不必添加任何注释@Repository 或@EnableJpa 等。
【讨论】:
【参考方案2】:我遇到了完全相同的问题。当我检查 maven 构建日志时,我意识到 hibernate 包有一个错误,抱怨“无效的 LOC 标头(错误的签名)”。我通过删除 .m2\repository\org\hibernate\hibernate-core 下的子目录并重新编译我的项目来解决。
【讨论】:
+1 它对我有用。 m2\repository\org\hibernate\hibernate-core 文件夹中有 3 个 hibernate-core jar 文件。我删除了所有并再次更新了maven项目。【参考方案3】:您缺少存储库配置,因为您必须使用 @Repository
进行配置,
以下不正确,
public interface UsuarioRepository extends JpaRepository<Usuario, Long>
而是应该如下配置为仓库,
@Repository
public interface UsuarioRepository extends JpaRepository<Usuario, Long>
这将使它成为一个被扫描的 bean 并将其视为存储库,然后您的以下代码也应该按预期工作,
@Autowired
private UsuarioRepository usuarioDao;
【讨论】:
【参考方案4】:在您的ClienteSpringApplication
中,您只有@SpringBootApplication
注释,这相当于@Configuration
、@EnableAutoConfiguration
和@ComponentScan
。您缺少的是 @EnableJpaRepositories
注释。
package es.uc3m.tiw;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableJpaRepositories
public class ClienteSpringApplication
public static void main(String[] args)
SpringApplication.run(ClienteSpringApplication.class, args);
如果它不起作用,请尝试添加存储库的包:
@EnableJpaRepositories("es.uc3m.tiw.dominios")
【讨论】:
【参考方案5】:检查您是否在 JpaRepository 上添加了 @Repository 注释 检查您是否使所有实体 Setter 和 Getter 清洁和建造 然后运行。
【讨论】:
【参考方案6】:pom.xml 需要更新,它对我有用:
我添加了以下依赖:
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
【讨论】:
【参考方案7】:检查 pom 文件中的 persistence-api 并尝试使用 spring-boot-started-data-jpa jar 的一部分 hibernate-jpa-2.1 进行更改
【讨论】:
【参考方案8】:在我的例子中是 h2-1.4.193.jar,它包含 Driver 类但无法读取(很奇怪,可能已损坏),如您所见: Driver class from h2-1.4.193
因此,您可以将 de spring-boot-starter-parent 更新为 1.5.3.RELEASE(或更高版本)或覆盖您的 h2 依赖项的托管版本。
【讨论】:
【参考方案9】:小心 Maven 加载的 jars 依赖项,在我的情况下,hibernate-core.jar 已损坏,一旦我删除并安装了该依赖项,项目运行正常。 干杯。
【讨论】:
以上是关于Spring Data JPA - 考虑在您的配置中定义一个名为“entityManagerFactory”的bean的主要内容,如果未能解决你的问题,请参考以下文章
考虑在您的配置中定义一个名为“entityManagerFactory”的 bean。3
Spring-data-jpa + Hibernate 未创建预期表
Spring Boot 自动配置无法与 spring-data-jpa 一起正常工作
微服务 第六章 springboot 通过Spring-data-jpa 配置Oracle数据源(Spring-data-jpa详细介绍)