web-dev-qa-db-ja.com

DDL実行のためにJDBC接続を開くことができません

私の春の豆で次のエラーが発生します、

「employeeRepositoryDAOImple」という名前のBeanの作成中にエラーが発生しました:メソッド「setSessionFactory」のパラメーター0によって表現された、満たされていない依存関係。ネストされた例外はorg.springframework.beans.factory.BeanCreationException:クラスパスリソース[config.xml]で定義された名前「sessionFactory」のBeanの作成エラー:initメソッドの呼び出しに失敗しました。ネストされた例外はorg.hibernate.exception.JDBCConnectionException:DDL実行のためにJDBC接続を開くことができません

Client.Java

public class Client {
    public static void main(String arg[]) {

        AbstractApplicationContext ctx = new     ClassPathXmlApplicationContext("config.xml");
        EmployeeService employeeService = (EmployeeService) ctx.getBean("empoyeService");

        Employee employee1 = new Employee(100001, "Alex", "Account");
        Employee employee2 = new Employee(100002, "Sam", "HR");

        employeeService.insert(employee1);
        employeeService.insert(employee2);
        System.out.println("Records are successfully added..");
        ctx.close();

    }
}

Entity.Java

@Entity
public class Employee {
@Id
private int empId;
private String empName;
private String department;
public Employee() {
    super();
}
public Employee(int empId,String empName,String deptName)
{
    super();
    this.empId=empId;
    this.empName=empName;
    this.department=deptName;
}

public int getEmpId() {
    return empId;
}
public void setEmpId(int empId) {
    this.empId = empId;
}
public String getEmpName() {
    return empName;
}
public void setEmpName(String empName) {
    this.empName = empName;
}
public String getDepartment() {
    return department;
}
public void setDepartment(String department) {
    this.department = department;
}
@Override
public String toString()
{
    return "Employee Empid="+empId+" empName="+empName+" department="+department;
}


}

EmployeeService.Java

@Service("empoyeService")
public class EmployeeServiceImpl implements EmployeeService {
@Autowired
EmployeeRepository emprepo;
@Override
public void insert(Employee employee) {
    // TODO Auto-generated method stub
    emprepo.insert(employee);
}

@Override
public int delete(int empid) {
    // TODO Auto-generated method stub
    return emprepo.delete(empid);
}

}
EmployeeRepositoryDAOImple.Java
   @Repository
   public class EmployeeRepositoryDAOImple implements EmployeeRepository{
private SessionFactory sessionFactory;
@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}
@Override
public void insert(Employee employee) {
    // TODO Auto-generated method stub
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    session.save(employee);
    tx.commit();
    session.close();

}}

Config.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Define Service and Repository beans using auto scan feature of         Spring -->
<context:component-scan base-package="com.orm.employee.dao,com.orm.employee.Service" />

<!-- Define DataSource bean using DriverManagerDataSource class of Spring --> 
<bean id="myDataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/myschema"></property>
    <property name="username" value="root"></property>
    <property name="password" value="xxxx"></property>
</bean>
<!-- Define sessionFactory bean of Spring class -->
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
    <property name="dataSource" ref="myDataSource" />
    <property name="packagesToScan" value="com.orm.employee.dao" />
    <property name="hibernateProperties">
        <value>
            hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
            hibernate.hbm2ddl.auto=update

        </value>
    </property>
</bean>
Exception
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.Apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception in thread "main"      org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'employeeRepositoryDAOImple': Unsatisfied dependency expressed through method 'setSessionFactory' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [config.xml]: Invocation of init method failed; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.Java:676)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.Java:90)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.Java:374)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.Java:1378)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.Java:575)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.Java:498)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.Java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.Java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.Java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.Java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.Java:846)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.Java:863)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.Java:546)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.Java:144)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.Java:85)
at com.orm.employee.client.Client.main(Client.Java:14)
Caused by: org.springframework.beans.factory.BeanCreationException:      Error creating bean with name 'sessionFactory' defined in class path resource [config.xml]: Invocation of init method failed; nested exception is org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.Java:1745)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.Java:576)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.Java:498)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.Java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.Java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.Java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.Java:199)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.Java:273)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.Java:1237)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.Java:1164)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredMethodElement.inject(AutowiredAnnotationBeanPostProcessor.Java:668)
... 15 more
Caused by: org.hibernate.exception.JDBCConnectionException: Unable to open JDBC Connection for DDL execution
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.Java:48)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.Java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.Java:113)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.Java:99)
at org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl.getIsolatedConnection(DdlTransactionIsolatorNonJtaImpl.Java:69)
at org.hibernate.tool.schema.internal.exec.ImprovedExtractionContextImpl.getJdbcConnection(ImprovedExtractionContextImpl.Java:60)
at org.hibernate.tool.schema.internal.exec.ImprovedExtractionContextImpl.getJdbcDatabaseMetaData(ImprovedExtractionContextImpl.Java:67)
at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.getTables(InformationExtractorJdbcDatabaseMetaDataImpl.Java:329)
at org.hibernate.tool.schema.extract.internal.DatabaseInformationImpl.getTablesInformation(DatabaseInformationImpl.Java:120)
at org.hibernate.tool.schema.internal.GroupedSchemaMigratorImpl.performTablesMigration(GroupedSchemaMigratorImpl.Java:65)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.Java:207)
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.Java:114)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.Java:183)
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.Java:72)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.Java:310)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.Java:467)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.Java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.Java:724)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.Java:615)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.Java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.Java:1804)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.Java:1741)
... 25 more
Caused by:     com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Client does not support authentication protocol requested by server; consider upgrading MySQL client
at Sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at Sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.Java:62)
at Sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.Java:45)
at Java.lang.reflect.Constructor.newInstance(Constructor.Java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.Java:353)
at com.mysql.jdbc.Util.getInstance(Util.Java:336)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.Java:985)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.Java:957)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.Java:2938)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.Java:855)
at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.Java:3337)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.Java:1217)
at com.mysql.jdbc.Connection.createNewIO(Connection.Java:1930)
at com.mysql.jdbc.Connection.<init>(Connection.Java:716)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.Java:46)
at Sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at Sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.Java:62)
at Sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.Java:45)
at Java.lang.reflect.Constructor.newInstance(Constructor.Java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.Java:353)
at com.mysql.jdbc.Connection.getInstance(Connection.Java:295)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.Java:266)
at Java.sql.DriverManager.getConnection(DriverManager.Java:664)
at Java.sql.DriverManager.getConnection(DriverManager.Java:208)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.Java:154)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.Java:145)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.Java:205)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.Java:169)
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.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl.getIsolatedConnection(DdlTransactionIsolatorNonJtaImpl.Java:43)
... 42 more
7
Aarthi Ananth

私の場合、rootユーザーに適切な認証権限がありませんでした。私はそれを知っていました。

須藤mysql

したがって、MySQLにログインしたら、次のように入力しました。

SELECT user、authentication_string、plugin、Host FROM mysql.user;

また、rootユーザーのプラグイン列で値auth_socketを確認しました。だから、私はそれを入力しました:

ALTER USER 'root' @ 'localhost' IDENTIFIED WITH mysql_native_password BY 'PASSWORD';

その後、Tomcatを再起動して問題を解決しました。

以降、mysqlにログインする必要があります。

mysql -u root -pPASSWORD

それが誰かを助けることを願っています:)

1
hfunes.com
Check you are hibernating configuration

spring.datasource.url=jdbc:mysql://localhost:3306/spring_boot_db
spring.datasource.username=root
spring.datasource.password=r00t
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform = org.hibernate.dialect.MySQL5Dialect
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto = update
1
Ganesh Giri

コードに次の変更を加えることができますか?.

<property name="hibernateProperties">
     <props>
        <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
        <prop key="hibernate.hbm2ddl.auto">update</prop>
    </props>
</property>

以下のプロパティを追加して、@AutowiredをsessionFactoryから削除します

<bean id="employeeDAO" class="yourbasepackage.EmployeeRepositoryDAOImple"> 
  <property name="sessionFactory" ref="sessionFactory" />
</bean>
0
Sabesh