hibernate xml配置似乎不起作用

时间:2017-12-26 14:30:04

标签: java hibernate

我正在学习hibernate,并试图使xml配置似乎不起作用。

hibernate.cfg.xml中

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//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.password">87654321</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/protein_tracker</property>

  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.default_schema">protein_tracker</property>
  <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.show_sql">true</property>
  <property name="hibernate.hbm2ddl.auto">create</property>
  <mapping resource="com/andrei/User.hbm.xml"/>
 </session-factory>
</hibernate-configuration>

<property name="hibernate.hbm2ddl.auto">create</property>不起作用。我得到例外:数据库中没有可用的表。

User.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="com.andrei.User" table="Users">
    <id name="id" type="int">
        <column name="ID" />
        <generator class="identity" />
    </id>
    <property name="name" type="java.lang.String">
        <column name="NAME" />
    </property>
    <property name="total" type="int">
        <column name="TOTAL" />
    </property>
    <property name="goal" type="int">
        <column name="GOAL" />
    </property>
</class>
</hibernate-mapping>

在user.hbm.xml中,我指定该表是用户,但该应用查找表用户,这正是我的实体的名称。

User.class:

@Entity
//@Table(name="users")  
public class User {

@Id
private int id;
private String name;
private int total;
private int goal;

public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public int getTotal() {
    return total;
}
public void setTotal(int total) {
    this.total = total;
}
public int getGoal() {
    return goal;
}
public void setGoal(int goal) {
    this.goal = goal;
}

}

如果我从用户类中取消注释@Table注释,该应用会查找正确的(用户)表。为什么xml配置不起作用?

Bellow你可以看到 hibernate助手类,以及我的 main()

HibernateUtilities.java

public class HibernateUtilities {

private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;

static {
    try {
        Configuration conf = new Configuration().configure();
        conf.addAnnotatedClass(com.andrei.User.class);
        conf.configure();

        serviceRegistry = new StandardServiceRegistryBuilder().applySettings(conf.getProperties()).build();
        sessionFactory = conf.buildSessionFactory(serviceRegistry);
    } catch (HibernateException e) {
        System.out.println("problem creating session factory: " + e);
    }
}

public static SessionFactory getSessionFactory() {
    return sessionFactory;
}
}

Main.java

public static void main(String[] args) {
    Session session = HibernateUtilities.getSessionFactory().openSession();
    session.beginTransaction();

    User user = new User();
    user.setName("first name");
    user.setGoal(250);

    session.save(user);

    session.getTransaction().commit();
    session.close();
    HibernateUtilities.getSessionFactory().close();

}

以下是我的问题

  1. 为什么xml配置不起作用? user.hbm.xml 中指定的表名是用户,但应用程序会查找表用户。
  2. 为什么<property name="hibernate.hbm2ddl.auto">create</property>不起作用?
  3. 以下是我的日志:

      

    Hibernate:drop table如果存在用户12月26日,2017 4:55:42 PM   org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl   getIsolatedConnection信息:HHH10001501:从中获取连接   JdbcConnectionAccess   [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@4612b856]   for(非JTA)DDL执行未处于自动提交模式;该   连接&#39;本地交易&#39;将提交和连接   将被设置为自动提交模式。 Hibernate:创建表用户(id   整数非空,目标整数不为空,名称为varchar(255),总计   整数非空,主键(id))type = MyISAM Dec 26,2017 4:55:42   下午   org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl   getIsolatedConnection信息:HHH10001501:从中获取连接   JdbcConnectionAccess   [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@74eb909f]   for(非JTA)DDL执行未处于自动提交模式;该   连接&#39;本地交易&#39;将提交和连接   将被设置为自动提交模式。 2017年12月26日下午4:55:42   org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl   handleException WARN:GenerationTarget遇到异常接受   command:通过JDBC语句执行DDL时出错   org.hibernate.tool.schema.spi.CommandAcceptanceException:错误   通过JDBC语句执行DDL   org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67)     在   org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:440)     在   org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlStrings(SchemaCreatorImpl.java:424)     在   org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCreatorImpl.java:315)     在   org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:166)     在   org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:135)     在   org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:121)     在   org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:155)     在   org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72)     在   org.hibernate.internal.SessionFactoryImpl。(SessionFactoryImpl.java:313)     在   org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:452)     在   org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)     在com.andrei.HibernateUtilities。(HibernateUtilities.java:21)     在com.andrei.Program.main(Program.java:8)引起:   com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:你有一个   SQL语法错误;查看与您的手册相对应的手册   MySQL服务器版本的正确语法使用附近&#39; type = MyISAM&#39;在   第1行   sun.reflect.NativeConstructorAccessorImpl.newInstance0(本机方法)     在   sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)     在   sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)     at java.lang.reflect.Constructor.newInstance(Constructor.java:423)     在com.mysql.jdbc.Util.handleNewInstance(Util.java:425)at   com.mysql.jdbc.Util.getInstance(Util.java:408)at   com.mysql.jdbc.SQLError.createSQLException(SQLError.java:944)at at   com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)at at   com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)at at   com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)at at   com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)at at   com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2480)at   com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2438)at   com.mysql.jdbc.StatementImpl.executeInternal(StatementImpl.java:845)     在com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:745)at   org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54)     ......还有13个

         

    2017年12月26日下午4:55:42   org.hibernate.tool.schema.internal.SchemaCreatorImpl   applyImportSources INFO:HHH000476:执行导入脚本   &#39; org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@2826f61'   Hibernate:插入用户(目标,名称,总数,ID)值(?,?,?,   ?)2017年12月26日下午4:55:42   org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions WARN:   SQL错误:1146,SQLState:42S02 Dec 26,2017 4:55:42 PM   org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions错误:   表&#39; protein_tracker.users&#39;不存在12月26日,2017 4:55:42 PM   org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release   信息:HHH000010:在批量发布时,它仍包含JDBC   声明2017年12月26日下午4:55:42   org.hibernate.internal.ExceptionMapperStandardImpl   mapManagedFlushFailure错误:HHH000346:托管刷新期间出错   [org.hibernate.exception.SQLGrammarException:无法执行   声明]线程中的异常&#34; main&#34;   javax.persistence.PersistenceException:   org.hibernate.exception.SQLGrammarException:无法执行   声明在   org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:149)     在   org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:157)     在   org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:164)     在org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1443)     在   org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:493)     在   org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3207)     在   org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2413)     在   org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:473)     在   org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:156)     在   org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access $ 100(JdbcResourceLocalTransactionCoordinatorImpl.java:38)     在   org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl $ TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:231)     在   org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68)     在com.andrei.Program.main(Program.java:17)引起:   org.hibernate.exception.SQLGrammarException:无法执行   声明在   org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)     在   org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)     在   org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)     在   org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)     在   org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:178)     在   org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45)     在   org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3013)     在   org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3513)     在   org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89)     在   org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:589)     在   org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463)     在   org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:337)     在   org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)     在org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1437)     ... 9更多引起:   com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:表   &#39; protein_tracker.users&#39;不存在于   sun.reflect.NativeConstructorAccessorImpl.newInstance0(本机方法)     在   sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)     在   sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)     at java.lang.reflect.Constructor.newInstance(Constructor.java:423)     在com.mysql.jdbc.Util.handleNewInstance(Util.java:425)at   com.mysql.jdbc.Util.getInstance(Util.java:408)at   com.mysql.jdbc.SQLError.createSQLException(SQLError.java:944)at at   com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973)at at   com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909)at at   com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527)at at   com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680)at at   com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2484)at   com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858)     在   com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2079)     在   com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2013)     在   com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5104)     在   com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1998)     在   org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175)     ......还有18个

    以上其中一条:

    Hibernate: create table users (id integer not null, goal integer not null, name varchar(255), total integer not null, primary key (id)) type=MyISAM
    

    但在此之后,有一个例外我不明白。在mySql中,没有创建表。

    非常感谢,祝你新年快乐!

2 个答案:

答案 0 :(得分:2)

我不确定,只需按照文档Hibernate_doc

Configuration cfg = new Configuration()
    .addClass(com.andrei.User.class)

在这种情况下,hibernate将为此类User.hbm.xml进行搜索配置。注意配置文件应该放在声明的类附近。

而不是

conf.addAnnotatedClass(com.andrei.User.class);

关于第二个问题。你在哪里找到配置文件hibernate.cfg.xml ??

答案 1 :(得分:1)

你应该使用(或实现)自定义的NamingStrategy类来映射classname&#34; User&#34;到tablename&#34;用户。有关详细信息,请参阅spring - hibernate 5 naming strategy configuration