Ошибка конфигурации гибернации! - PullRequest
0 голосов
/ 22 мая 2011

У меня есть 5 файлов 3 xml и 2 java (для подключения и выполнения HQL-запроса), 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.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://host:3306/wwwgeeksearthcom_geeksearth_test</property>
    <property name="hibernate.connection.username">username</property>
    <property name="hibernate.connection.password">******</property>
    <property name="hibernate.show_sql">true</property>
    <mapping resource="hibernate.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

hibernate.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="client">
<class name="HiberTest" table="guests">
  <id name="id" column="g_id">
      <generator class="native"/>
  </id>
</class>
</hibernate-mapping>

hibernate.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
  <schema-selection match-catalog="wwwgeeksearthcom_geeksearth_test"/>
  <table-filter match-name="guests"/>
</hibernate-reverse-engineering>

HiberTest.java

import org.hibernate.*;
import org.hibernate.cfg.*;
import java.util.*;


public class HiberTest {

  private static SessionFactory sessionFactory;

  private int id;

  protected static void setUp() throws Exception {
      // A SessionFactory is set up once for an application
      sessionFactory = new Configuration()
              .configure() // configures settings from hibernate.cfg.xml
              .buildSessionFactory();
  }

  public static void main(String[] args) throws Exception {
    setUp();
    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    Query q = session.createQuery("from guests");
        List resultList = q.list();
        System.out.println(resultList);
        session.getTransaction().commit();
        session.close();
  }

}

HibernateUtil.java

import org.hibernate.cfg.*;
import org.hibernate.SessionFactory;

/**
 * Hibernate Utility class with a convenient method to get Session Factory object.
 *
 * @author arthurkushman
 */
public class HibernateUtil {
    private static final SessionFactory sessionFactory = buildSessionFactory();
    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            return new Configuration().configure().buildSessionFactory();
        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

Ошибка:

Exception in thread "main" org.hibernate.hql.ast.QuerySyntaxException: guests is not mapped [from guests]
        at org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:158)
        at org.hibernate.hql.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:87)
        at org.hibernate.hql.ast.tree.FromClause.addFromElement(FromClause.java:70)
        at org.hibernate.hql.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:255)
        at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3056)
        at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:2945)
        at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:688)
        at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:544)
        at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:281)
        at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:229)
        at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:228)
        at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:160)
        at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:111)
        at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
        at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:56)
        at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:72)
        at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:133)
        at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:112)
        at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1623)
        at HiberTest.main(HiberTest.java:27)
Java Result: 1

1 Ответ

3 голосов
/ 22 мая 2011

HQL-запросы должны указывать класс сущности, а не имя таблицы.

Глядя на ваше отображение, это означает "from HiberTest" вместо "from guests".

Сказав это, ваш пример не имеет смысла. class, указанный в отображении, должен ссылаться на постоянный класс сущностей (например, Guest), который отображается в вашу таблицу базы данных guests. Ваш класс HiberTest является частью тестовой логики и не имеет ничего общего с отображением.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...