简体   繁体   中英

why isn't this JPA query returning a list of my specific class?

I have a JPA object:

@Entity
@Table(name="WF_GROUP")
public class Group {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private long id;
  private String groupName;
  private long parentId;

/* ... */

}

I have a GroupDAO with this method:

public List<Group> getAllGroups() {
  List<Group> groups = new ArrayList<Group>();
  String query = "select * from WF_GROUP";
  Query q = getEntityManager().createNativeQuery(query);
  groups.addAll( q.getResultList() );
  return groups;
}

The problem is the q.getResultList() returns a result list of type Object than contains an object array for each property.

Why doesn't q.getResultList() return a list of Group objects?

Thanks! Rob

Because you don't specify which class the native query should return. Have a look at the other createNativeQuery methods, taking additional arguments.

Note that the point of using JPA is to use objects rather than database tables. JPQL is there for that. You should use the following code:

String query = "select group from Group group"; // this is JPQL
TypedQuery<Group> q = getEntityManager().createQuery(query, Group.class);
groups.addAll(q.getResultList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM