2
votes

I'am learning to use java since few weeks et i want to use Hibernate in simple Java console application. I download the last version of Hibernate ORM (4.3.8)

I add this Jars in my ClassPath :

  • com.mysql.jdbc_5.1.5.jar
  • sqlite-jdbc-3.8.7.jar
  • Hibernate Library\antlr-2.7.7.jar
  • Hibernate Library\dom4j-1.6.1.jar
  • Hibernate Library\hibernate-commons-annotations-4.0.5.Final.jar
  • Hibernate Library\hibernate-core-4.3.8.Final.jar
  • Hibernate Library\hibernate-jpa-2.1-api-1.0.0.Final.jar
  • Hibernate Library\jandex-1.1.0.Final.jar
  • Hibernate Library\javassist-3.18.1-GA.jar
  • Hibernate Library\jboss-logging-3.1.3.GA.jar
  • Hibernate Library\jboss-logging-annotations-1.2.0.Beta1.jar
  • Hibernate Library\jboss-transaction-api_1.2_spec-1.0.0.Final.jar

My Class :

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

@Entity
@Table(name = "STUDENT_INFORMATIONS")
public class Student_Info {

    @Id
    private int rollNo;

    private String name;


    public int getRollNo() {
        return rollNo;
    }
    public void setRollNo(int rollNo) {
        this.rollNo = rollNo;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}

My Main Code :

    Student_Info student = new Student_Info();
    student.setName("Fabien");
    student.setRollNo(1);


    SessionFactory sessionFactory;
    ServiceRegistry serviceRegistry;

    Configuration configuration = new Configuration();
    configuration.configure();

    serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
            configuration.getProperties()).build();
    sessionFactory = configuration.buildSessionFactory(serviceRegistry);

    Session session = sessionFactory.openSession();
    session.beginTransaction();

    session.save(student);

    session.getTransaction().commit();
    session.close();
    sessionFactory.close();

SQLite

First i create an hibernate.cfg.xml configuration for SQLite with dialect property to "util.SQLiteDialect"

<?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="show_sql">true</property>
                <property name="format_sql">true</property>
                <property name="dialect">util.SQLiteDialect</property>
                <property name="connection.driver_class">org.sqlite.JDBC</property>
                <property name="connection.url">jdbc:sqlite:SQLiteJDBC.sqlite</property>
                <property name="connection.username"></property>
                <property name="connection.password"></property>

                <!--  create / update  -->
                <property name="hibernate.hbm2ddl.auto">create</property>

                <!--  Liste des classes à Mapper en base de données -->
                <!--  <mapping resource="User.hbm.xml"/> -->
                <mapping class="com.hibernate.Student_Info"/>
        </session-factory>
</hibernate-configuration>

When i run my main program i have this error :

...
INFO: HHH000006: Autocommit mode: false
janv. 10, 2015 4:23:40 PM org.hibernate.engine.jdbc.connections.internal.DriverM
anagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Exception in thread "main" org.hibernate.boot.registry.selector.spi.StrategySele
ctionException: Unable to resolve name [util.SQLiteDialect] as strategy [org.hib
ernate.dialect.Dialect]
    at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStr
ategyImplementor(StrategySelectorImpl.java:128)
    at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveDe
faultableStrategy(StrategySelectorImpl.java:155)
    at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveSt
rategy(StrategySelectorImpl.java:136)
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.constructDiale
ct(DialectFactoryImpl.java:78)
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(D
ialectFactoryImpl.java:68)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesIm
pl.java:165)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureSe
rvice(StandardServiceRegistryImpl.java:111)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService
(AbstractServiceRegistryImpl.java:234)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(Abstra
ctServiceRegistryImpl.java:206)
    at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:18
87)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
    at com.hibernate.Main.main(Main.java:26)

MySql

After i tried with a mysql Database

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM 
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

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

        <!--  JDBC Connection pool  -->
        <property name="connection.pool_size">1</property>

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

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

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


        <!--  create / update  -->
        <property name="hibernate.hbm2ddl.auto">create</property>

        <!--  Liste des classes à Mapper en base de données -->
        <!--  <mapping resource="User.hbm.xml"/> -->
        <mapping class="com.hibernate.Student_Info"/>

    </session-factory>
</hibernate-configuration>

When i run my main programm i have this error :

...
janv. 10, 2015 4:41:43 PM org.hibernate.engine.jdbc.connections.internal.DriverM
anagerConnectionProviderImpl buildCreator
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://local
host:3306/hierbnate]
janv. 10, 2015 4:41:43 PM org.hibernate.engine.jdbc.connections.internal.DriverM
anagerConnectionProviderImpl buildCreator
INFO: HHH000046: Connection properties: {user=root, password=****}
janv. 10, 2015 4:41:43 PM org.hibernate.engine.jdbc.connections.internal.DriverM
anagerConnectionProviderImpl buildCreator
INFO: HHH000006: Autocommit mode: false
janv. 10, 2015 4:41:43 PM org.hibernate.engine.jdbc.connections.internal.DriverM
anagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 1 (min=1)
Exception in thread "main" org.hibernate.exception.SQLGrammarException: Error ca
lling Driver#connect
    at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLState
ConversionDelegate.java:123)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.co
nvert(BasicConnectionCreator.java:118)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.conver
tSqlException(BasicConnectionCreator.java:140)
    at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeC
onnection(DriverConnectionCreator.java:58)
    at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.create
Connection(BasicConnectionCreator.java:75)
    at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProvid
erImpl.configure(DriverManagerConnectionProviderImpl.java:106)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureSe
rvice(StandardServiceRegistryImpl.java:111)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService
(AbstractServiceRegistryImpl.java:234)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(Abstra
ctServiceRegistryImpl.java:206)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAcces
s(JdbcServicesImpl.java:260)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesIm
pl.java:94)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureSe
rvice(StandardServiceRegistryImpl.java:111)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService
(AbstractServiceRegistryImpl.java:234)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(Abstra
ctServiceRegistryImpl.java:206)
    at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:18
87)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
    at com.hibernate.Main.main(Main.java:25)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown da
tabase 'hierbnate'
    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:406)
    at com.mysql.jdbc.Util.getInstance(Util.java:381)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1031)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3376)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3308)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:894)
    at com.mysql.jdbc.MysqlIO.secureAuth411(MysqlIO.java:3808)
    at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1256)
    at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2032)
    at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:729)
    at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:46)
    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:406)
    at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:302)
    at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:283)
    at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeC
onnection(DriverConnectionCreator.java:55)
    ... 13 more

1 - Do you know if is it possible to use hibernate on SQLite ?

2 - If yes, do you know why it doesn't works ?

3 - For MySql, what is the problem ?

thank you very much !!

2

2 Answers

2
votes

Thanks to Todd for my Syntaxe Error (MySql).

For SQLite, the dialect is not present in hibernate 4.3. So i found and adapt a classe for use SQLite with Hibernate 4.3.8 :

/*
 * The author disclaims copyright to this source code.  In place of
 * a legal notice, here is a blessing:
 * 
 *    May you do good and not evil.
 *    May you find forgiveness for yourself and forgive others.
 *    May you share freely, never taking more than you give.
 *
 */
package org.hibernate.dialect;

import java.sql.Types;

import org.hibernate.dialect.function.StandardSQLFunction;
import org.hibernate.dialect.function.SQLFunctionTemplate;
import org.hibernate.dialect.function.VarArgsSQLFunction;
import org.hibernate.type.IntegerType;
import org.hibernate.type.StringType;
import org.hibernate.Hibernate;


public class SQLiteDialect extends Dialect {
  public SQLiteDialect() {
    registerColumnType(Types.BIT, "integer");
    registerColumnType(Types.TINYINT, "tinyint");
    registerColumnType(Types.SMALLINT, "smallint");
    registerColumnType(Types.INTEGER, "integer");
    registerColumnType(Types.BIGINT, "bigint");
    registerColumnType(Types.FLOAT, "float");
    registerColumnType(Types.REAL, "real");
    registerColumnType(Types.DOUBLE, "double");
    registerColumnType(Types.NUMERIC, "numeric");
    registerColumnType(Types.DECIMAL, "decimal");
    registerColumnType(Types.CHAR, "char");
    registerColumnType(Types.VARCHAR, "varchar");
    registerColumnType(Types.LONGVARCHAR, "longvarchar");
    registerColumnType(Types.DATE, "date");
    registerColumnType(Types.TIME, "time");
    registerColumnType(Types.TIMESTAMP, "timestamp");
    registerColumnType(Types.BINARY, "blob");
    registerColumnType(Types.VARBINARY, "blob");
    registerColumnType(Types.LONGVARBINARY, "blob");
    // registerColumnType(Types.NULL, "null");
    registerColumnType(Types.BLOB, "blob");
    registerColumnType(Types.CLOB, "clob");
    registerColumnType(Types.BOOLEAN, "integer");

    registerFunction( "concat", new VarArgsSQLFunction(StringType.INSTANCE, "", "||", "") );
    registerFunction( "mod", new SQLFunctionTemplate( IntegerType.INSTANCE, "?1 % ?2" ) );
    registerFunction( "substr", new StandardSQLFunction("substr", StringType.INSTANCE) );
    registerFunction( "substring", new StandardSQLFunction( "substr", StringType.INSTANCE ) );
  }

  public boolean supportsIdentityColumns() {
    return true;
  }

  /*
  public boolean supportsInsertSelectIdentity() {
    return true; // As specify in NHibernate dialect
  }
  */

  public boolean hasDataTypeInIdentityColumn() {
    return false; // As specify in NHibernate dialect
  }

  /*
  public String appendIdentitySelectToInsert(String insertString) {
    return new StringBuffer(insertString.length()+30). // As specify in NHibernate dialect
      append(insertString).
      append("; ").append(getIdentitySelectString()).
      toString();
  }
  */

  public String getIdentityColumnString() {
    // return "integer primary key autoincrement";
    return "integer";
  }

  public String getIdentitySelectString() {
    return "select last_insert_rowid()";
  }

  public boolean supportsLimit() {
    return true;
  }

  protected String getLimitString(String query, boolean hasOffset) {
    return new StringBuffer(query.length()+20).
      append(query).
      append(hasOffset ? " limit ? offset ?" : " limit ?").
      toString();
  }

  public boolean supportsTemporaryTables() {
    return true;
  }

  public String getCreateTemporaryTableString() {
    return "create temporary table if not exists";
  }

  public boolean dropTemporaryTableAfterUse() {
    return false;
  }

  public boolean supportsCurrentTimestampSelection() {
    return true;
  }

  public boolean isCurrentTimestampSelectStringCallable() {
    return false;
  }

  public String getCurrentTimestampSelectString() {
    return "select current_timestamp";
  }

  public boolean supportsUnionAll() {
    return true;
  }

  public boolean hasAlterTable() {
    return false; // As specify in NHibernate dialect
  }

  public boolean dropConstraints() {
    return false;
  }

  public String getAddColumnString() {
    return "add column";
  }

  public String getForUpdateString() {
    return "";
  }

  public boolean supportsOuterJoinForUpdate() {
    return false;
  }

  public String getDropForeignKeyString() {
    throw new UnsupportedOperationException("No drop foreign key syntax supported by SQLiteDialect");
  }

  public String getAddForeignKeyConstraintString(String constraintName,
      String[] foreignKey, String referencedTable, String[] primaryKey,
      boolean referencesPrimaryKey) {
    throw new UnsupportedOperationException("No add foreign key syntax supported by SQLiteDialect");
  }

  public String getAddPrimaryKeyConstraintString(String constraintName) {
    throw new UnsupportedOperationException("No add primary key syntax supported by SQLiteDialect");
  }

  public boolean supportsIfExistsBeforeTableName() {
    return true;
  }

  public boolean supportsCascadeDelete() {
    return false;
  }

  @Override
  public boolean bindLimitParametersInReverseOrder() {
      return true;
  }

}
1
votes

I think you might have just spelled "hibernate" wrong...

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'hierbnate'

Try changing this:

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hierbnate</property>

To this:

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate</property>

(Unless your db is really called hierbnate, and then I'll just delete this answer).