当没有可用连接时,必须设置hibernate.dialect

时间:2014-07-26 09:00:27

标签: java database eclipse hibernate

这是我的Person.java类

  package com.hibernate.project.pos.model;
import javax.persistence.*;

@Entity
@Table(name="testdb")
public class Person {

    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="id")
    private Long id;
    @Column(name="first", unique=true, length=100)
    private String firstName;
    @Column(name="last", unique=true, length=100)
    private String lastName;

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

这是我的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.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testdb</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.hbm2ddl.auto">create</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.format_sql">true</property>
    <mapping class="com.hibernate.project.pos.model.Person" />
  </session-factory>
</hibernate-configuration>

MainHibernate.java类

package com.hibernate.project.pos.model;
import java.util.List;

import javax.imageio.spi.ServiceRegistry;
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistryBuilder;

public class MainHibernate {
    public static void main(String[] args) {

        @SuppressWarnings("deprecation")
        SessionFactory sessionFactory =  new Configuration().buildSessionFactory();

        Person p = new Person();
         p.setFirstName("dian");
         p.setLastName("bodat");

        Session session = sessionFactory.openSession();

        try{
            session.beginTransaction();
            session.save(p);
            session.getTransaction().commit();
        }catch(HibernateException hibernateException){
            session.getTransaction().rollback();
        }
        session.close();

        session = sessionFactory.openSession();
        Query query = session.createQuery("from testdb");
        List<Person> persons = query.list();
        for(Person person : persons){
            System.out.println("id: "+person.getId());
            System.out.println("first name : "+person.getFirstName());
            System.out.println("last name : "+person.getLastName());
        }
        session.close();
        sessionFactory.close();

    }
}

这是我的数据库

CREATE DATABASE testdb;
CREATE TABLE names(
   id integer auto_increment primary key,
   'first' varchar(100) unique not null,
   'last' varchar(100) not null
) ENGINE=InnoDB;

这是我的错误

SLF4J: Defaulting to no-operation (NOP) logger implementation

SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

Exception in thread "main" org.hibernate.HibernateException: 'hibernate.dialect' must be set when no Connection available

 at org.hibernate.dialect.resolver.DialectFactory.buildDialect(DialectFactory.j  ava:106)

 at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:152)

 at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:28  63)

 at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2859)

 at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1870  )

 at com.googlecode.projecttempelate.pos.model.MainJdbc.main(MainJdbc.java:47)

我正在使用jre 7,以及hibernate-release-4.1.5.SP1和所需的库 我也想使用注释映射,而不是xml映射

提前谢谢^^


感谢你的回答^^

编辑MainHibernate类

后出现错误
/*add .configure()*/
        SessionFactory sessionFactory =  new Configuration().configure().buildSessionFactory();

错误是

Jul 26, 2014 4:58:23 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
Jul 26, 2014 4:58:23 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.1.5.SP1}
Jul 26, 2014 4:58:23 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jul 26, 2014 4:58:23 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Jul 26, 2014 4:58:23 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Jul 26, 2014 4:58:23 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Jul 26, 2014 4:58:24 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Jul 26, 2014 4:58:24 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Jul 26, 2014 4:58:24 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Jul 26, 2014 4:58:24 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
Jul 26, 2014 4:58:24 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
Jul 26, 2014 4:58:24 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/testdb]
Jul 26, 2014 4:58:24 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=root}
Jul 26, 2014 4:58:25 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Jul 26, 2014 4:58:25 PM org.hibernate.engine.jdbc.internal.LobCreatorBuilder useContextualLobCreation
INFO: HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
Jul 26, 2014 4:58:25 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Jul 26, 2014 4:58:25 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
Jul 26, 2014 4:58:25 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
Hibernate: 
    drop table if exists names
Hibernate: 
    create table names (
        id bigint not null auto_increment,
        first varchar(100) unique,
        last varchar(100) unique,
        primary key (id)
    )
Jul 26, 2014 4:58:26 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate: 
    insert 
    into
        names
        (first, last) 
    values
        (?, ?)
Exception in thread "main" org.hibernate.hql.internal.ast.QuerySyntaxException: testdb is not mapped [from testdb]
    at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:180)
    at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:110)
    at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:93)
    at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:324)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3291)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3180)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:706)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:562)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:299)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:247)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:248)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:183)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:105)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:168)
    at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:219)
    at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:197)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1736)
    at com.hibernate.project.pos.model.MainHibernate.main(MainHibernate.java:35)

----------

感谢您的回答,大家好 我的第一个编辑是关注@Suman的帖子 我的第二次编辑是关注@Luca Basso Ricci的帖子 现在它正常工作^^

4 个答案:

答案 0 :(得分:1)

我怀疑对您的代码进行以下更正(MainHibernate.java类)可能会解决问题。

    @SuppressWarnings("deprecation")
    SessionFactory sessionFactory =  new Configuration().**configure().**buildSessionFactory();

更正是在buildSessionFactory()之前使用configure()方法。

以下是我用作参考的主题。

'hibernate.dialect' must be set when no Connection available error

由于

答案 1 :(得分:1)

Person @Table(name="testdb")是否正确?为什么不是@Table(name="names")? 除了看你的代码

Query query = session.createQuery("from testdb");

应该是

Query query = session.createQuery("from Person");

因为HQL查询使用@Entity,而不是原始表(这就是 testdb没有映射[来自testdb] 的原因,因为 testdb 不是@Entity

答案 2 :(得分:0)

您缺少hibernate.connection.password属性。尝试添加它,看看它是否有帮助。

答案 3 :(得分:0)

在Main中尝试:(对于Hibernate 4.x)

Configuration cfg = new Configuration();

cfg.configure("hibernate.cfg.xml");    
ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
SessionFactory sessionFactory = cfg.buildSessionFactory(sr);