문제

I have a rather big model Applicant:

public class Applicant{
 private Long id
 private String name;
 ...
 ...
}

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());
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top