JPA Typed Search Queries
I have a rather big model Applicant:
public class Applicant{
private Long id
private String name;
...
.开发者_如何学C..
}
To populate a selection list, I need a list of (id, name) tuples and I use this search query:
public List getNames() {
Query query = em.createQuery("select a.id, a.name from Applicant a");
return query.getResultList();
}
However, I get a list of Object[]'s and I don't really want to convert these in the business layer to the corresponding types (Long and String). What is the best way to approach this? Should I iterate through the list and manually do the type conversion before returning it? Or should I make a helper class:
public class ApplicantTuple{
public Long id
public String name;
public Application(Long id, String name) {
...
}
}
and then have a search query:
Query query = em.createQuery("select NEW my.model.ApplicantTuple(a.id, a.name) from Applicant a");
Or is there a better way to type search queries?
Since you're apparently using JPA2, use the type-safe methods:
public List<Applicant> getApplicants() {
TypedQuery<Applicant> query = em.createQuery(
"select a.id, a.name from Applicant a",
Applicant.class
);
return query.getResultList();
}
Then just use the Objects:
for(Applicant app: getApplicants()){
selectionList.populate(app.getName(), app.getId());
}
精彩评论