hibernate: how to select all rows in a table
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();
You can use
session.createCriteria(MyEntity.class).list();
for example.
ref: Retrieving all rows of a table without HQL?
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 Object
s 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