terça-feira, 17 de junho de 2008

JPA List e List JSF

Adaptei um método publicado aqui para fazer a conversão genérica de um List (que é o retorno de uma consulta JPA) para um List que é utilizado pelos comboboxes no JSF. O método é um draft, pode ser otimizado, mas em fim, é uma sugestão. Penso que facilita a vida.
Para se utilizar, se passa a lista, uma o nome do campo ID (como string) e o nome do campo de descrição (também como string). O retorno é um List


public List<SelectItem> getItems(List entities, String idGetMthdName, String descGetMthdName) {
List<SelectItem> items = new Vector<SelectItem>();
try {
Method idMthd = null, nameMthd = null;
for (int i = 0; i < entities.size(); i++) {
Object entity = entities.get(i);
// On the first run, initialize reflection methods for object
if (idMthd == null) {
Class entityClass = entity.getClass();
idMthd = entityClass.getMethod(idGetMthdName, new Class[]{});
nameMthd = entityClass.getMethod(descGetMthdName, new Class[]{});
}
// Retrieve values on the
//Integer id = (Integer)idMthd.invoke(entity, new Object[]{});
String id = (String) idMthd.invoke(entity, new Object[]{});
String name = (String) nameMthd.invoke(entity, new Object[]{});
//System.out.println("id=" + id);
//System.out.println("name=" + name);
// Add key information to select item list
// System.out.println("------------------------");
SelectItem item = new SelectItem();
item.setLabel(name);
item.setValue(id.toString());
items.add(item);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//System.out.println("Fim");
return items;
}