JPA Hibernate Persistence 异常 [PersistenceUnit: default] 无法构建 Hibernate SessionFactory

Posted

技术标签:

【中文标题】JPA Hibernate Persistence 异常 [PersistenceUnit: default] 无法构建 Hibernate SessionFactory【英文标题】:JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory 【发布时间】:2016-09-20 04:09:50 【问题描述】:

我一直在尝试使用 JPA Hibernate 和 mysql 解决与我的数据库的连接,但由于某种原因,无论我尝试什么,在启动 tomcat 服务器时我都会遇到同样的异常:

 org.springframework.beans.factory.BeanCreationException: Error creating     bean with name 'localContainerEntityManagerFactoryBean' defined in class path resource [core/JPAConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'localContainerEntityManagerFactoryBean' threw exception; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory

这是我的 JPA 配置类:

@Configuration
@EnableJpaRepositories("core.repository")
@EnableTransactionManagement
@EnableCaching
public class JPAConfig 

@Value("$db.jdbcURL")
private String jdbcURL;

@Value("$db.user")
private String user;

@Value("$db.password")
private String password;

@Value("$db.generateDDL")
private Boolean generateDDL;

@SuppressWarnings("Duplicates")
@Bean
public DataSource dataSource() 
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(Driver.class.getName());
    dataSource.setUrl("jdbc:mysql://localhost:3306/movierentaldb");
    dataSource.setUsername(System.getProperty("root"));
    dataSource.setPassword(System.getProperty("mdie1767"));
    dataSource.setInitialSize(2);
    dataSource.setMaxActive(5);
    return dataSource;


@Bean
public LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean()
    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setDatabase(Database.MYSQL);
    vendorAdapter.setGenerateDdl(generateDDL);
    vendorAdapter.setShowSql(true);

    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();

    factory.setJpaVendorAdapter(vendorAdapter);

    factory.setPackagesToScan("core.model");

    factory.setDataSource(dataSource());

    factory.afterPropertiesSet();
    return factory;


@Bean
public EntityManagerFactory entityManagerFactory()
    return localContainerEntityManagerFactoryBean().getObject();




@Bean
public EntityManager entityManager()
    return entityManagerFactory().createEntityManager();


@Bean
PlatformTransactionManager transactionManager()
    JpaTransactionManager manager = new JpaTransactionManager();
    manager.setEntityManagerFactory(entityManagerFactory());
    return manager;


@Bean
public HibernateExceptionTranslator hibernateExceptionTranslator()
    return  new HibernateExceptionTranslator();


@Bean
public CacheManager cacheManager()
    GuavaCacheManager guavaCacheManager = new GuavaCacheManager();
    guavaCacheManager.setCacheBuilder(CacheBuilder.newBuilder().expireAfterAccess(2, TimeUnit.HOURS));
    return guavaCacheManager;

在这一点上,我想不出任何其他尝试..任何帮助都非常有义务

编辑:这是整个堆栈跟踪

23-May-2016 13:05:10.267 INFO [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log No Spring WebApplicationInitializer types detected on classpath
23-May-2016 13:05:10.444 INFO [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Initializing Spring root WebApplicationContext
23-May-2016 13:05:15.333 SEVERE [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.StandardContext.listenerStart Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
 org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'localContainerEntityManagerFactoryBean' defined in class path resource [core/JPAConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'localContainerEntityManagerFactoryBean' threw exception; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1123)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1018)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1054)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:829)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:444)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:326)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:107)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4732)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5194)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:152)
    at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:726)
    at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:702)
    at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
    at org.apache.catalina.startup.HostConfig.manageApp(HostConfig.java:1702)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
    at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:482)
    at org.apache.catalina.mbeans.MBeanFactory.createStandardContext(MBeanFactory.java:431)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
    at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
    at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
    at javax.management.remote.rmi.RMIConnectionImpl.doOperation(RMIConnectionImpl.java:1466)
    at javax.management.remote.rmi.RMIConnectionImpl.access$300(RMIConnectionImpl.java:76)
    at javax.management.remote.rmi.RMIConnectionImpl$PrivilegedOperation.run(RMIConnectionImpl.java:1307)
    at javax.management.remote.rmi.RMIConnectionImpl.doPrivilegedOperation(RMIConnectionImpl.java:1399)
    at javax.management.remote.rmi.RMIConnectionImpl.invoke(RMIConnectionImpl.java:828)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:323)
    at sun.rmi.transport.Transport$1.run(Transport.java:200)
    at sun.rmi.transport.Transport$1.run(Transport.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.Transport.serviceCall(Transport.java:196)
    at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:568)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(TCPTransport.java:826)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$240(TCPTransport.java:683)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler$$Lambda$1/108265094.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:682)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean]: Factory method 'localContainerEntityManagerFactoryBean' threw exception; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 60 more
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: default] Unable to build Hibernate SessionFactory
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:884)
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:319)
    at core.JPAConfig.localContainerEntityManagerFactoryBean(JPAConfig.java:94)
    at core.JPAConfig$$EnhancerBySpringCGLIB$$c2bcf261.CGLIB$localContainerEntityManagerFactoryBean$1(<generated>)
    at core.JPAConfig$$EnhancerBySpringCGLIB$$c2bcf261$$FastClassBySpringCGLIB$$901863a2.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:355)
    at core.JPAConfig$$EnhancerBySpringCGLIB$$c2bcf261.localContainerEntityManagerFactoryBean(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    ... 61 more
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Unable to obtain JDBC Connection
    at org.hibernate.tool.schema.internal.exec.AbstractJdbcConnectionContextImpl.getConnection(AbstractJdbcConnectionContextImpl.java:46)
    at org.hibernate.tool.schema.internal.exec.ImprovedExtractionContextImpl.getJdbcConnection(ImprovedExtractionContextImpl.java:59)
    at org.hibernate.tool.schema.internal.exec.ImprovedExtractionContextImpl.getJdbcDatabaseMetaData(ImprovedExtractionContextImpl.java:66)
    at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.getTable(InformationExtractorJdbcDatabaseMetaDataImpl.java:271)
    at org.hibernate.tool.schema.internal.exec.ImprovedDatabaseInformationImpl.getTableInformation(ImprovedDatabaseInformationImpl.java:109)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.performMigration(SchemaMigratorImpl.java:252)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:137)
    at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:110)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:176)
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:64)
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:458)
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:881)
    ... 75 more
Caused by: org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Access denied for user ''@'localhost' (using password: NO))
    at org.apache.commons.dbcp.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:1549)
    at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1388)
    at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
    at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180)
    at org.hibernate.tool.schema.internal.exec.AbstractJdbcConnectionContextImpl.getConnection(AbstractJdbcConnectionContextImpl.java:43)
    ... 87 more
Caused by: java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:695)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:663)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:653)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:108)
    at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:1683)
    at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:656)
    at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:349)
    at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:221)
    at org.apache.commons.dbcp.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:38)
    at org.apache.commons.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:582)
    at org.apache.commons.dbcp.BasicDataSource.validateConnectionFactory(BasicDataSource.java:1556)
    at org.apache.commons.dbcp.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:1545)
    ... 92 more

23-May-2016 13:05:15.379 INFO [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.core.ApplicationContext.log Closing Spring root WebApplicationContext
Error:(7, 24) java: package org.gjt.mm.mysql does not exist

【问题讨论】:

你能分享整个堆栈(错误)跟踪吗? 检查你的配置,这可能是System.getProperty("root")..的原因 【参考方案1】:

问题是您无法连接到 MYSQL 数据库,因此它会抛出一个错误,说无法构建会话工厂。

请看下面的错误:

 Caused by: java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO) 

指向username 没有得到populated

请重新检查系统属性

dataSource.setUsername(System.getProperty("root"));

一些包似乎也丢失了,这表明存在依赖问题:

package org.gjt.mm.mysql does not exist

请运行mvn dependency:tree 命令检查依赖关系

【讨论】:

在再次编译、打包和安装 maven 父项目之后,我设法运行了一个依赖项:树,它解决了我的 deps。此外, sys 属性也无处可寻,所以我硬编码了精确的 url 字符串。现在它部署没有问题。非常感谢【参考方案2】:

我发现了一些关于这种错误的问题

    mysql 或其他数据库中的数据库用户名或密码不匹配。请像这样设置application.properties

  

# ===============================
# = DATA SOURCE
# ===============================

# Set here configurations for the database connection

# Connection url for the database please let me know "mondolmislam@gmail.com"
spring.datasource.url = jdbc:mysql://localhost:3306/bookstoreapiabc

# Username and secret
spring.datasource.username = root
spring.datasource.password =

# Keep the connection alive if idle for a long time (needed in production)
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1

# ===============================
# = JPA / HIBERNATE
# ===============================

# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager).

# Show or not log for each sql query
spring.jpa.show-sql = true

# Hibernate ddl auto (create, create-drop, update): with "update" the database
# schema will be automatically updated accordingly to java entities found in
# the project
spring.jpa.hibernate.ddl-auto = update

# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

第 2 期。

您的本地服务器有两个数据库服务器并且这些数据库服务器冲突。这种冲突就像 mysql server & xampp or lampp or wamp server。请像 mysql server 这样的数据库之一,因为 xampp 或 lampp server 会自动在这台机器上安装 mysql server

【讨论】:

嗨,我使用的是事务类型 JTA,我可以在连接和发布所有 jndi 路由的日志中看到,但最后在服务器启动之前给我这些错误,我正在使用甲骨文【参考方案3】:

即使所有相关的依赖项都已到位,我也会收到此错误,因为我没有在 MySQL 中创建架构。

我以为它会自动创建,但事实并非如此。虽然会创建表本身,但您必须创建架构。

【讨论】:

是的,所有表都是在pass中创建的,事务类型为jta。这个 EJB 模块在 jboss 7 中运行良好,但我正在将它迁移到 wildfly 20.0.1,现在给我这个错误【参考方案4】:

我最后有一个分号,并给了我这个错误。

【讨论】:

女巫文件末尾的分号?【参考方案5】:

由于命名查询中的错误而出现此错误。

【讨论】:

你怎么解决的,我所有的模型实体都在记录没有映射? 在我的休眠版本 (5.4.19.Final) 中,命名查询在 org.hibernate.internal.SessionFactoryImpl 的构造函数中在第 327 行附近进行检查。如果命名了断点,您会收到明确的错误消息启用查询检查(这应该是默认设置)。

以上是关于JPA Hibernate Persistence 异常 [PersistenceUnit: default] 无法构建 Hibernate SessionFactory的主要内容,如果未能解决你的问题,请参考以下文章

JPA Hibernate Persistence 异常 [PersistenceUnit: default] 无法构建 Hibernate SessionFactory

Spring JPA (Hibernate) 没有符合条件的 bean 类型:javax.persistence.EntityManagerFactory

persistence-demo之jpa

JPA javax.persistence.PersistenceException:org.hibernate.MappingException:没有 JDBC 类型的方言映射:-101

Hibernate JPA 的异常

JPA persistence.xml 和 MySQL - 没有采用正确的“hibernate.connection.url”目录