Hibernate: how to select all rows in a table
I am trying 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 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 an exception:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to de.motza.entities.LogEntry
I know the problem is casting the query result to an object, but I can't find anywhere how to create objects correctly or how to get more than one row from a table.
Does anyone have any advice? If required I can post my persistence.xml file and more
source to share
Since you were using nativeQuery, you need to pass the result using the method setResultTransormer
.
Query query = manager.createNativeQuery("SELECT * FROM " + tableName + ";");
query.setResultTransformer(Transformers.aliasToBean(LogEntry.class))
ArrayList<LogEntry> entries = (ArrayList<LogEntry>) query.getResultList();
source to share
The "problem" is that you are submitting your own query that returns an Object [] array, one value for each column. You don't have to call your own request, but for example a hibernate request ...
manager.createQuery("SELECT l FROM LogEntry");
see this answer for example .
source to share
First, you should try to use HQL, Hibernate Query Language. In the above example, you are trying to execute a native SQL query. The reason you get ClassCastException
is because your own query traverses the structure and returns raw Object
instead of the one you want.
Try using this code instead SELECT *
:
String hql = "from LogEntry";
Session session = entityManagerFactory.openSession();
Query query = session.createQuery(hql);
List<LogEntry> logEntries = query.list(); // no ClassCastException here
source to share
As I know getResultList () gives you a list ... not a generic list. Therefore, if you want to get a general list, you should use
TypedQuery<Person>
insted
Query
This is the link where I got the information.
Cast something to the result of Query.getResultList ()?
I don't know anything about Hibernate. I hope this helps you.
source to share