Failed to create table using Hibernate and MYSQL

I am new to hibernate and I need to get some strange behavior, below is the scenario.

My java files:

UserDetails.java: -

package org.mahesh.test;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class UserDetails {
@Id
private int userId;
private String userName;
public String getUserName() {
    return userName;
}
public void setUserName(String userName) {
    this.userName = userName;
}
public int getUserId() {
    return userId;
}
public void setUserId(int userId) {
    this.userId = userId;
}   
}

      

HibernateTest.java is,

 package org.mahesh.hibernate;
 import org.hibernate.Session;
 import org.hibernate.SessionFactory;
 import org.hibernate.cfg.Configuration;
 import org.mahesh.securifi.UserDetails;
 public class HibernateTest {

 public static void main(String[] args) {
    // TODO Auto-generated method stub
    UserDetails user = new UserDetails();
    user.setUserId(1);
    user.setUserName("Mahesh");

    SessionFactory sessionFactory = new   Configuration().configure().buildSessionFactory();
    Session session = sessionFactory.openSession();
    session.beginTransaction();
    session.save(user);
    session.getTransaction().commit();
  }
  }

      

hibernate.cfg.xml is,

   <?xml version='1.0' encoding='utf-8'?>
   <!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

 <hibernate-configuration>

<session-factory>

    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/employee</property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>

    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

    <!-- Disable the second-level cache  -->
    <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>

    <!-- Drop and re-create the database schema on startup -->
    <property name="hibernate.hbm2ddl.auto">create</property>

    <!-- Names the annotated entity class -->
    <mapping class="org.mahesh.securifi.UserDetails"/>

</session-factory>

</hibernate-configuration>

      

Full stack trace,

Mar 24, 2017 10:28:20 AM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.9.Final}
Mar 24, 2017 10:28:20 AM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Mar 24, 2017 10:28:20 AM         org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Mar 24, 2017 10:28:20 AM     org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderIm    pl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for     production use!)
Mar 24, 2017 10:28:20 AM     org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderIm    pl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL     [jdbc:mysql://localhost:3306/employee]
Mar 24, 2017 10:28:20 AM     org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderIm    pl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
Mar 24, 2017 10:28:20 AM     org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderIm    pl buildCreator
INFO: HHH10001003: Autocommit mode: false
Mar 24, 2017 10:28:20 AM     org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Mar 24, 2017 10:28:20 AM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Mar 24, 2017 10:28:20 AM     org.hibernate.engine.jdbc.env.internal.LobCreatorBuilderImpl     useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported     JDBC version [3] less than 4
Hibernate: drop table if exists UserDetails
Mar 24, 2017 10:28:21 AM     org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorN    onJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess     [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProvi    derJdbcConnectionAccess@40db2a24] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: create table UserDetails (userId integer not null, userName     varchar(255), primary key (userId)) type=MyISAM
Mar 24, 2017 10:28:21 AM     org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorN    onJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess     [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@22356acd] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Mar 24, 2017 10:28:21 AM     org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException
WARN: GenerationTarget encountered exception accepting command : Error     executing DDL via JDBC Statement
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement
at     org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)
at     org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreato    rImpl.java:440)
at     org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlStrings(SchemaCreat    orImpl.java:424)
at         org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCr    eatorImpl.java:315)
at     org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreat    orImpl.java:166)
at     org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImp    l.java:135)
at     org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImp    l.java:121)
at     org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAct    ion(SchemaManagementToolCoordinator.java:155)
at     org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaMana    gementToolCoordinator.java:72)
at org.hibernate.internal.SessionFactoryImpl.<init>    (SessionFactoryImpl.java:309)
at     org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilde    rImpl.java:445)
at     org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
at     org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at org.mahesh.hibernate.HibernateTest.main(HibernateTest.java:16)
Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an         error in your SQL syntax; check the manual that corresponds to your MySQL server     version for the right syntax to use near 'type=MyISAM' at line 1
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3277)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3206)
    at com.mysql.jdbc.Statement.execute(Statement.java:727)
    at     org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(Genera    tionTargetToDatabase.java:54)
... 13 more

Mar 24, 2017 10:28:21 AM     org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script     'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@6e4566    f1'
Hibernate: insert into UserDetails (userName, userId) values (?, ?)
Mar 24, 2017 10:28:21 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper         logExceptions
WARN: SQL Error: 1146, SQLState: 42S02
Mar 24, 2017 10:28:21 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper     logExceptions
ERROR: Table 'employee.userdetails' doesn't exist
Mar 24, 2017 10:28:21 AM     org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
Mar 24, 2017 10:28:21 AM org.hibernate.internal.ExceptionMapperStandardImpl     mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush     [org.hibernate.exception.SQLGrammarException: could not execute statement]
Exception in thread "main" javax.persistence.PersistenceException:     org.hibernate.exception.SQLGrammarException: could not execute statement
    at     org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.jav    a:147)
at     org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.jav    a:155)
at     org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.jav    a:162)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1434)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:484)
at     org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.    java:3190)
at     org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:    2404)
at     org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompleti    on(JdbcCoordinatorImpl.java:467)
at     org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransa        ctionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordi    natorImpl.java:146)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransa        ctionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java    :38)
at     org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransa    ctionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransa    ctionCoordinatorImpl.java:220)
at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl    .java:68)
at org.mahesh.hibernate.HibernateTest.main(HibernateTest.java:20)
Caused by: org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3003)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3503)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:586)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:460)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1428)
... 9 more
Caused by: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table     'employee.userdetails' doesn't exist
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
at com.mysql.jdbc.Connection.execSQL(Connection.java:3283)
at         com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1332)
at     com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1604)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1519)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1504)
at     org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetRe    turnImpl.java:205)
... 18 more

      

Getting this error while running.

+3


source to share


4 answers


Try to change the dialect in hibernate.cfg.cml

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>

      

This should fix the problem.

If you want to use MyISAM



package com.mahesh.dialect;
import org.hibernate.dialect.MySQLMyISAMDialect

class MySQL5MyISAMDialect extends MySQLMyISAMDialect {
   String getTableTypeString() {
      " ENGINE=MyISAM"
   }
}

      

and set the dialect to

<!-- SQL dialect -->
<property name="dialect">com.mahesh.dialect.MySQL5MyISAMDialect</property>

      

+2


source


org.hibernate.dialect.MySQL5InnoDBDialect

deprecated.

Deprecated use of "hibernate.dialect.storage_engine = innodb" variable or JVM system property.



You can put hibernate.dialect.storage_engine=innodb

in hibernate.properties or set it in an environment variable.

+1


source


This exception is because there are no UserDetails tables in the database if you want hibernate to create the table add below property to your hibernate.cfg.xml file

<property name="hbm2ddl.auto">create</property>

      

you can choose the value hbm2ddl.auto validate | update | create | creation-fall depends on your requirement.

0


source


I also had CommandAcceptanceException and SQLGrammarException when I upgraded my DB from MySQL 5.1 to 5.7. I changed the dialect in hibernate.cfg.xml

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

      

This was previously "org.hibernate.dialect.MySQLDialect". This fixed the problem.

0


source







All Articles