Im querying a database using JPQL but I cannot retrieve the ‘Report’ table’s rows using List. This is a section of my code:
...
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hibernate");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
Query query = em.createQuery("SELECT r.title, r.company FROM Report as r");
List<Report> itemList = query.getResultList();
for (Report item : itemList)
{
System.out.println("Item: " + item.getCompany());
}
The output is:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to maps.Report at hello.Test.main(Unknown Source)
Java Result: 1
What am I doing wrong? Why I am not allowed to do the casting?
Your query doesn’t select instances of
Report. It selects two fields:r.titleandr.company. In this case, JPA returns a list ofObject[]. EachObject[]of the list contains two elements: the title and the company.Use
select r from Report rto selectReportinstances.