#hibernate
#гибернация
Вопрос:
У меня есть 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:
Запросы HQL должны указывать класс объекта, а не имя таблицы.
Глядя на ваше отображение, это означает "from HiberTest"
, вместо "from guests"
.
Сказав это, ваш пример не имеет смысла. class
Указанное в сопоставлении должно относиться к постоянному классу объектов (например Guest
), который сопоставлен с вашей guests
таблицей базы данных. Ваш HiberTest
класс является частью тестовой логики и не имеет ничего общего с отображением.
Комментарии:
1. хороший ответ, чувак, я бы поставил тебе точку — спасибо, и что я должен написать в Guest.java — какой идентификатор (и другие поля) и методы получения, установки?