Answer the question
In order to leave comments, you need to log in
Why is sql query not executing in Hibernate?
Hello. Help please solve the problem.
I am writing a function that shows a table from a database. I am using MySQL dialect
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
public void getTariffsList() {
Session session = Factory.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
String sql = "FROM Tariff";
System.out.println(sql);
List tariffs = session.createQuery(sql).list();
for (Iterator iterator =
tariffs.iterator(); iterator.hasNext(); ) {
Tariff tariff = (Tariff) iterator.next();
System.out.print("id: " + tariff.getId());
System.out.print(" title: " + tariff.getTitle());
System.out.println();
}
transaction.commit();
} catch (HibernateException e) {
if (transaction != null) transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
List tariffs = session.createSQLQuery(sql).list();
String sql = "Select * FROM Tariff";
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to DAO.Hibirnate.Tariff
List tariffs = session.createSQLQuery(sql).list();
and how to fix it.
Answer the question
In order to leave comments, you need to log in
Your error is due to the fact that hibernate returns a List and doesn't know what the type will be at compile time. You need to add a conversion to the type you need.
Try
and @SuppressWarnings("unchecked") if warnings are confusing.
In order for Hibernate to return objects of a specific type from a SQL query, this type must be explicitly specified using the addEntity() method:
And the question is - why use SQL in this case?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question