0
votes

I am learning hibernate, and trying to make xml configuration which seems not to work.

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>

The <property name="hibernate.hbm2ddl.auto">create</property> does not work. I get exception: no available table in the database.

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>

In the user.hbm.xml I specify that the table is users, but the app looks for table user, which is exactly the name name of my entity.

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;
}

}

If I uncomment the @Table annotation from the user class, the app looks for the correct (users) table. Why the xml configuration is not working?

Bellow you can see the hibernate helper class, and my 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();

}

Here are my questions

  1. Why the xml configuration does not work? The table name specified in user.hbm.xml is users, but the app looks for table user.
  2. Why <property name="hibernate.hbm2ddl.auto">create</property> does not work?

Here are my logs:

Hibernate: drop table if exists users Dec 26, 2017 4:55:42 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@4612b856] 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 users (id integer not null, goal integer not null, name varchar(255), total integer not null, primary key (id)) type=MyISAM Dec 26, 2017 4:55:42 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@74eb909f] 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. Dec 26, 2017 4:55:42 PM 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(SchemaCreatorImpl.java:440) at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlStrings(SchemaCreatorImpl.java:424) at org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCreatorImpl.java:315) at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:166) at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:135) at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:121) at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:155) at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72) at org.hibernate.internal.SessionFactoryImpl.(SessionFactoryImpl.java:313) at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:452) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710) at com.andrei.HibernateUtilities.(HibernateUtilities.java:21) at com.andrei.Program.main(Program.java:8) Caused by: com.mysql.jdbc.exceptions.jdbc4.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 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:425) at com.mysql.jdbc.Util.getInstance(Util.java:408) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:944) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680) 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) at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:745) at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54) ... 13 more

Dec 26, 2017 4:55:42 PM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@2826f61' Hibernate: insert into users (goal, name, total, id) values (?, ?, ?, ?) Dec 26, 2017 4:55:42 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions WARN: SQL Error: 1146, SQLState: 42S02 Dec 26, 2017 4:55:42 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions ERROR: Table 'protein_tracker.users' doesn't exist Dec 26, 2017 4:55:42 PM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release INFO: HHH000010: On release of batch it still contained JDBC statements Dec 26, 2017 4:55:42 PM 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.java:149) at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:157) at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:164) at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1443) at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:493) at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3207) at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2413) at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:473) at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.beforeCompletionCallback(JdbcResourceLocalTransactionCoordinatorImpl.java:156) at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl.access$100(JdbcResourceLocalTransactionCoordinatorImpl.java:38) at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.commit(JdbcResourceLocalTransactionCoordinatorImpl.java:231) at org.hibernate.engine.transaction.internal.TransactionImpl.commit(TransactionImpl.java:68) at com.andrei.Program.main(Program.java:17) Caused by: org.hibernate.exception.SQLGrammarException: could not execute statement at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63) 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:178) at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:45) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3013) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3513) at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:89) at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:589) at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:463) 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:1437) ... 9 more Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'protein_tracker.users' doesn't exist 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:425) at com.mysql.jdbc.Util.getInstance(Util.java:408) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:944) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3973) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3909) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2527) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2680) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2484) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1858) at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2079) at com.mysql.jdbc.PreparedStatement.executeUpdateInternal(PreparedStatement.java:2013) at com.mysql.jdbc.PreparedStatement.executeLargeUpdate(PreparedStatement.java:5104) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1998) at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175) ... 18 more

One of the lines above:

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

but after this, there is an exception which I don't understand. In mySql, there is no table created.

Thank you very much and a happy new year!

2

2 Answers

1
votes

I am not sure, just follow documentation Hibernate_doc

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

in this case hibernate will be search configuration for this class User.hbm.xml. Pay attention the config files should be placed near declared class.

instead of

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

About second question. Where do you situated the configuration file hibernate.cfg.xml ??

1
votes

You should use (or implement) custom NamingStrategy class in order to map classname "User" to tablename "Users. See for details spring - hibernate 5 naming strategy configuration