Java Hibernate MySQL 无法创建表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18962263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:55:56  来源:igfitidea点击:

Hibernate MySQL Cant create table

javamysqlhibernate

提问by Azaro

Im learning hibernate and i got stuck at the very beginning. So the problem is that my app cant auto-create table. Here goes all the code:

我正在学习休眠,一开始就被卡住了。所以问题是我的应用程序无法自动创建表。下面是所有代码:

hibernate.cfg.xml

休眠文件.cfg.xml

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

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatedb</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">password</property>
        <property name="hibernate.connection.pool_size">1</property>
        <property name="hibernate.hbm2dll.auto">create</property>   
        <property name="hibernate.show_sql">true</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <mapping class="azaro.test.hibernate.UserDetails" />    
    </session-factory>
</hibernate-configuration>

HibernateTest.java

休眠测试.java

package azaro.test.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateTest {

    public static void main(String[] args) {
        UserDetails user = new UserDetails();
        user.setUserId(1);
        user.setUserName("First User");

        Configuration configuration = new Configuration();
        configuration.configure();
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();        
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(user);
        session.getTransaction().commit();
    }

}

UserDetails.java

用户详细信息.java

package azaro.test.hibernate;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class UserDetails {
    @Id
    private int userId;
    private String userName;

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

}

And the console output:

和控制台输出:

Hibernate: insert into UserDetails (userName, userId) values (?, ?)
Sep 23, 2013 6:34:23 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1146, SQLState: 42S02
Sep 23, 2013 6:34:23 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Table 'hibernatedb.userdetails' doesn't exist
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:82)
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:136)
    at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:58)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3067)
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3509)
    at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:88)
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:377)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:369)
    at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:286)
    at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:339)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:52)
    at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1234)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:404)
    at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
    at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175)
    at azaro.test.hibernate.HibernateTest.main(HibernateTest.java:23)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'hibernatedb.userdetails' doesn't exist
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.Util.getInstance(Util.java:386)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1054)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4190)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4122)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2570)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2731)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2818)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2157)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2460)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2377)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2361)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:133)
    ... 14 more

If you need more info, feel free to ask.

如果您需要更多信息,请随时询问。

采纳答案by Pratik Shelar

Check the ddl that is generated using

检查使用生成的ddl

SchemaExport(cfg).create(true, true);

Using this you will know the ddl and can analyze better. Also if schema is already updated. Set hbm2ddl.auto to 'create-drop'

使用它,您将了解 ddl 并可以更好地进行分析。此外,如果架构已经更新。将 hbm2ddl.auto 设置为 'create-drop'

回答by Prabhakaran Ramaswamy

Please try org.hibernate.dialect.MySQL5InnoDBDialectinstead of org.hibernate.dialect.MySQLDialect

请尝试org.hibernate.dialect.MySQL5InnoDBDialect代替org.hibernate.dialect.MySQLDialect

MySQL5Dialact refers to the MyISAM storage type and the MySQL5InnoDBDialect the InnoDB (newer) type.

MySQL5Dialact 指的是 MyISAM 存储类型,而 MySQL5InnoDBDialect 指的是 InnoDB(较新)类型。

回答by user1693371

add in configuration file(hibernate.cfg.xml) update and use @Column annotation to create column in databse

添加配置文件(hibernate.cfg.xml)更新并使用@Column注释在数据库中创建列

回答by vshan

do not initiate the user to null and configure hbm2ddl as create-drop, the code will execute with the result as follows:

不要将用户初始化为null并将hbm2ddl配置为create-drop,代码将执行,结果如下:

Hibernate: insert into USER_DETAILS (Address, description, joinedDate, userName, userId) values (?, ?, ?, ?, ?) Hibernate: select userdetail0_.userId as userId1_0_0_, userdetail0_.Address as Address2_0_0_, userdetail0_.description as descript3_0_0_, userdetail0_.joinedDate as joinedDa4_0_0_, userdetail0_.userName as userName5_0_0_ from USER_DETAILS userdetail0_ where userdetail0_.userId=?

Hibernate:插入 USER_DETAILS (Address, description,joinedDate, userName, userId) 值 (?, ?, ?, ?, ?) Hibernate:选择 userdetail0_.userId 作为 userId1_0_0_,userdetail0_.Address 作为 Address2_0_0_,userdetail0_.description 作为 descript3_0_0 .joinedDate asjoinedDa4_0_0_, userdetail0_.userName as userName5_0_0_ from USER_DETAILS userdetail0_ where userdetail0_.userId=?

user name retreived isfirst user

检索到的用户名是第一个用户

回答by elk

You have an error in the cfg.xmlfile. Change hbm2dllto hbm2ddlin

您在cfg.xml文件中有错误。更改hbm2 DLL到hbm2 DDL

"hibernate.hbm2dll.auto">create

Then life will be beautiful again. I know this because I made the same mistake and spent some hours to figure it out.

那么生活将再次美好。我知道这一点是因为我犯了同样的错误并花了几个小时才弄明白。

回答by Sarfaraz Shaikh

The 'SQLGrammarException' exception means the wrong syntax has written while the configuration of dialect.

'SQLGrammarException' 异常意味着在配置方言时写入了错误的语法。

Sep 23, 2013 6:34:23 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Table 'hibernatedb.userdetails' doesn't exist
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement
~~~~~~~~~~~~

Answer:

- The correct dialect entry is: [<property name="hibernate.dialect">]
  ~~~~~~~~~~
   <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> 
  ~~~~~~~~~

- The given is found from your XML file. [<property name="dialect">]
  ~~~~~~~~~
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <mapping class="azaro.test.hibernate.UserDetails" />    
    </session-factory>
    </hibernate-configuration>
  ~~~~~~~~~~~

Root Cause: The hibernate property should start with the 'hibernate.' prefix!

In this case, your code contains the property with the "dialect" prefix and this is wrong. Replace it with the "hibernate.dialect".


- Sarfaraz