web-dev-qa-db-ja.com

JPA Hibernate Persistence例外[PersistenceUnit:default] Hibernate SessionFactoryを構築できません

私はJPA Hibernateとmysqlを使用してDBへの接続を整理しようとしましたが、何らかの理由で、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
13
Joe Blow

問題は、MYSQLデータベースへの接続を取得できないため、セッションファクトリを構築できないというエラーがスローされることです。

以下のエラーをご覧ください:

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

usernamepopulatedを取得していないことを指します。

システムのプロパティを再確認してください

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

いくつかのパッケージは依存関係の問題を指しているだけでなく、欠落しているようです:

package org.gjt.mm.mysql does not exist

mvn dependency:treeコマンドを実行して依存関係を確認してください

13
shankarsh15

MySQLでスキーマを作成していないため、関連するすべての依存関係が設定されていても、このエラーが発生していました。

自動的に作成されると思いましたが、そうではありませんでした。テーブル自体は作成されますが、スキーマを作成する必要があります。

1
Himanshu Shukla

その種のエラーに関する問題を見つけました

  1. データベースのユーザー名またはパスワードがmysqlまたは他のデータベースと一致しません。 application.propertiesをこのように設定してください
 

# =============================== # = DATA SOURCE # =============================== # Set here configurations for the database connection # Connection url for the database please let me know "[email protected]" 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。

ローカルサーバーには2つのデータベースサーバーがあり、それらのデータベースサーバーは競合しています。このような競合はmysql server&xamppまたはlamppまたはwamp serverです。 mysql serverなどのデータベースのいずれかを選択してくださいxamppまたはlampp serverこのマシンにmysql serverを自動的にインストールするため

0