P
P
parkito2016-08-17 13:39:37
MySQL
parkito, 2016-08-17 13:39:37

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>

The function written like this works
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();
        }

    }

However, when I want to use, List tariffs = session.createSQLQuery(sql).list();
by changing the request accordingly, the following exception takes off.
String sql = "Select * FROM Tariff";
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to DAO.Hibirnate.Tariff

Please tell me what is wrong List tariffs = session.createSQLQuery(sql).list();and how to fix it.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
sirs, 2016-08-17
@parkito

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.

A
Alexander Kosarev, 2016-08-17
@jaxtr

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 question

Ask a Question

731 491 924 answers to any question