7

I try to do something like Select * from LogEntry with Hibernate. insert works fine:

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

[...]
protected EntityManager manager;

protected final String tableName = "LogEntry";

public DatabaseImpl(DB_TYPE db) {
    this.db = db;
    if (entityManagerFactory != null && entityManagerFactory.isOpen()) {
        entityManagerFactory.close();
    }
    entityManagerFactory = Persistence.createEntityManagerFactory(db.getPersUnit());
    manager = entityManagerFactory.createEntityManager();
}
public void insert(LogEntry entry) {

    manager.getTransaction().begin();
    manager.persist(entry);
    manager.getTransaction().commit();
}

But when I try to get the inserted values using this method: public LogEntryList getAll() {

    manager.getTransaction().begin();

    Query query = manager.createNativeQuery("SELECT * FROM " + tableName + ";");
    ArrayList<LogEntry> entries = (ArrayList<LogEntry>) query.getResultList();
    manager.getTransaction().commit();

    return new LogEntryList(entries);
}

I always get the Exception: java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to de.motza.entities.LogEntry

I know the problem is the casting of the Query result to the object, but I can't find anywhere how to cast the objects properly, or how to get more than one row from the table.

does anybody have any advice? If requested, I can post my persistence.xml and more code

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
Ruth
  • 856
  • 2
  • 13
  • 26

7 Answers7

7

Becuase you have used nativeQuery so you need to transfer result by using setResultTransormer method.

Query query = manager.createNativeQuery("SELECT * FROM " + tableName + ";");
query.setResultTransformer(Transformers.aliasToBean(LogEntry.class))
ArrayList<LogEntry> entries = (ArrayList<LogEntry>) query.getResultList();
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
Sunil
  • 437
  • 3
  • 11
5

For starters, you should try to take advantage of HQL, Hibernate Query Language. In the example you gave above, you are trying to execute a native SQL query. The reason you are getting the ClassCastException is that the native query is circumventing the framework and returning raw Objects instead of the type you want.

Try using this code instead for your SELECT *:

String hql = "from LogEntry";
Session session = entityManagerFactory.openSession();
Query query = session.createQuery(hql);
List<LogEntry> logEntries = query.list();      // no ClassCastException here
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • 1
    While not exactly what the user wanted, this is certainly beneficial information. It was for me. Thank you for your answer @Tim Biegeleisen :) – Matthew Feb 24 '20 at 15:48
5

You can use session.createCriteria(MyEntity.class).list(); for example.

ref: Retrieving all rows of a table without HQL?

Community
  • 1
  • 1
Mahbub
  • 93
  • 1
  • 6
1

The "problem" is, that you are sending a native query which will return an Object[] array, with one value for each dolumn. You do not need to call a native query, but a hibernate query, for example...

manager.createQuery("SELECT l FROM LogEntry");

see, for example, this answer.

Community
  • 1
  • 1
Florian Schaetz
  • 10,454
  • 5
  • 32
  • 58
1

If you are using Spring HibernateDaoSupport, you can use these methods to load Entities from database:

a) single entity by ID

@Override
public DeleteProcessNotification getDeleteProcessNotificationById(Long id) {
    return this.getHibernateTemplate().load(DeleteProcessNotification.class, id);
}

b) all entities

@Override
public List<DeleteProcessNotification> getDeleteProcessNotificationsInQueue() {
    return this.getHibernateTemplate().loadAll(DeleteProcessNotification.class);
}

c) entities with a HQL query

@Override
public List<DeleteProcessNotification> getPrioritizedDeleteProcessNotifications() {
    return (List<DeleteProcessNotification>) this.getHibernateTemplate().find(
            "FROM DeleteProcessNotification dpn \n" +
                    "WHERE dpn.priority = 'HIGH'");
}

HibernateDaoSupport documentation: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/orm/hibernate5/support/HibernateDaoSupport.html

M. Merim
  • 45
  • 9
0

As i know getResultList() gives you a List...not a generic List. So if you want to get a generic list you have to use

TypedQuery<Person> 

insted of

Query

This is the link i got the information.

Cast to something the result of Query.getResultList()?

I don't know much about Hibernate. i hope this will help you.

Community
  • 1
  • 1
Tharkana
  • 1
  • 1
0
List<String> list = null;

TypedQuery<String> query = sessionfactory.openSession().createQuery("from yourTableName");

list = query.getResultList();

yourTableName can be your @Entity class

AS Mackay
  • 2,831
  • 9
  • 19
  • 25
Gol.D
  • 1