Java - Hibernate 连接数据库

Java - Hibernate connection database

几周以来我一直在学习使用 java,我想在简单的 Java 控制台应用程序中使用 Hibernate。 我下载最新版本的 Hibernate ORM (4.3.8)

我将这个 Jars 添加到我的 Class路径中:

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

}

我的主要代码:

    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

首先我为 SQLite 创建一个 hibernate.cfg.xml 配置,方言 属性 到 "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>

当我 运行 我的主程序时出现此错误 :

...
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

在我尝试使用 mysql 数据库后

<?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>

当我 运行 我的主程序出现这个错误时:

...
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.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 - 你知道是否可以在 SQLite 上使用休眠模式吗?

2 - 如果是,您知道它为什么不起作用吗?

3 - 对于 MySql,问题是什么?

非常感谢!!

我想你可能刚刚 "hibernate" 拼错了...

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

尝试改变这个:

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

为此:

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

(除非你的数据库真的叫hierbnate,那我就删掉这个答案)。

感谢 Todd 我的语法错误 (MySql)。

对于 SQLite,方言在 hibernate 4.3 中不存在。所以我找到并改编了一个类以将 SQLite 与 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;
  }

}