Ben
Ben

Reputation: 3

Java JPA EM.createNativeQuery(sql, someClass).getResultList()

How do I return a list of foobar as below?

@MappedSuperclass    
public abstract class foobar{}

@Entity
@Table(name="foobar")
public class foo extends foobar{}

@Entity
@Table(name="foobar")
public class bar extends foobar{}

List<foobar> results = em.createNativeQuery("SELECT * FROM foobar").getResultList();

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to foobar.

Upvotes: 0

Views: 6509

Answers (2)

petrus
petrus

Reputation: 1

Try this:

List<foobar> results = em.createNativeQuery("SELECT * FROM foobar", foobar.class).getResultList();

You must specify the class of the result to be cast.

Upvotes: 0

Neil Stockton
Neil Stockton

Reputation: 11531

An SQL query of the form "SELECT * FROM tbl" will return each row as Object[]. Hence you should do

List<Object[]> results = ...

To map to a specific result class (whatever your foobar is), follow this link. You can of course just use JPQL if wanting to map to entities.

Upvotes: 0

Related Questions