当前位置: 首页 > 知识库问答 >
问题:

无法使用Hibernate和MYSQL创建表

管景天
2023-03-14
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;
}   
}
 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();
  }
  }
   <?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>
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

运行时收到此错误。

共有1个答案

严宇
2023-03-14

尝试在hibernate.cfg.cml中更改方言

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

这样就可以解决问题了。

如果要使用MyISAM

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

class MySQL5MyISAMDialect extends MySQLMyISAMDialect {
   String getTableTypeString() {
      " ENGINE=MyISAM"
   }
}
<!-- SQL dialect -->
<property name="dialect">com.mahesh.dialect.MySQL5MyISAMDialect</property>
 类似资料:
  • 我在创建sessionFactory对象时遇到问题。我将Hibernate与Maven和MySQL一起使用。怎么修? 日志错误: xml(在src/main/resources中): users.hbm.xml(在src/main/users.hbm.xml中):

  • 我是春靴新来的,我需要你的帮助。我试图配置我的MySQL DB,JPA(Hibernate),但我遇到了以下异常: 创建类路径资源中定义的名为“实体ManagerFactory”的bean时出错。....

  • 我刚开始使用hibernate,总是会遇到这样的错误: 错误:HHH000388:不成功:创建表用户(id bigint not null auto_increment,mail varchar(255),passwort varchar(255),primary key(id))错误:从存储引擎获取错误-1 这是我的映射类:

  • 问题内容: 我试图将edmx实体模型添加到Visual Studio 2013中的C#/ Web项目中。我的问题是未创建文件。 我执行以下步骤: 给项目起个名字 从数据库中选择“ EF Designer” 从已经成功测试成功连接到MySQL数据库的下拉列表(localhost)中选择连接 选中“将webc.config中的连接设置另存为”选项 我单击“下一步”,窗口消失,然后回到代码窗口 没有创建

  • 我正在尝试使用文本文件的内容在MySQL数据库中创建存储过程: 我使用本机查询执行SQL: 但是它在DROP PROCEDURE上得到一个错误我注释了DROP PROCEDURE,然后它在DELIMITER上得到一个错误基本上,它在第一个分号之后的任何一行上都得到一个错误。 似乎JPA hibernate正在解析我的查询并告诉我它有问题,而不是将纯文本传递到MySQL。 sql在MySQL中运行,

  • 我尝试使用HikariCP池连接,但我无法启动应用程序,因为我一直在创建sesion中获取空对象。 这是我的配置: 系统 Hibernate4.3.6。最终 MariaDB v10.0(x64) HibernateUtil类 hibernate.cfg.xml 日志 正在准备使用过滤器构建会话工厂:{}hh000130:实例化显式连接提供程序:org.mariadb.jdbc。应用程序启动方法中的