这是我的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的帖子
现在它可以正常工作了^^

最佳答案

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

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


应该

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


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

09-16 13:40