Olá pessoal do GUJ, estou com uma dúvida de como projetar na consulta do Hibernate a quantidades de 'filhos' de uma relação 1:N. Vamos as classes:
public class Grupo{
private String nome;
@Transient
private int tamanhoListaSubgrupos, tamanhoListaItens;
@OneToMany(mappedBy = "grupo", fetch = FetchType.LAZY)
private List<Subgrupo> subgrupos;
@OneToMany(mappedBy = "grupo", fetch = FetchType.LAZY)
private List<Item> itens;
// get e set ....
}
public class Item{
private String nome;
@ManyToOne @JoinColumn(name = "fk_grupo")
private Grupo grupo;
//get, set e outros atributos
}
public class Subgrupo{
private String nome;
@ManyToOne @JoinColumn(name = "fk_grupo")
private Grupo grupo;
//get, set e outros atributos
}
select g.id as id_grupo, g.nome as nome_grupo,
(select count(*) from subgrupos s where g.id = s.fk_grupo) as total_subgrupos,
(select count(*) from itens i where g.id = i.fk_grupo) as total_itens
from grupos g
public List<Grupo> all() throws Exception {
Criteria c = session.createCriteria(Grupo.class,"g")
.setProjection(Projections.projectionList()
.add(Projections.property("g.id").as("id") )
.add(Projections.property("g.nome").as("nome") ) )
.setResultTransformer(new AliasToBeanResultTransformer(Grupo.class) );
List<Grupo> lista = c.list();
for(Grupo g : lista){
g.setTamanhoListaItens(getTotalItensGrupo(g.getId()));
g.setTamanhoListaSubgrupos(getTotalSubgrupoGrupo(g.getId()));
}
return lista;
}
getTotalItensGrupo(long id)
getTotalSubgrupoGrupo(long id)
Abraço a todos.
Jonh Paulo