Mostrando postagens com marcador projection. Mostrar todas as postagens
Mostrando postagens com marcador projection. Mostrar todas as postagens

segunda-feira, 24 de novembro de 2008

distinct com projection

Quando usamos projection, o "criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);"
algumas vezes não funciona pois faz o distinct após a consulta ser feita, o distinct correto é esse:

...
ProjectionList p = Projections.projectionList().create();
p.add(Projections.property("c.id"), "id");
p.add(Projections.property("c.nome"), "nome");
criteria.setProjection(p);

criteria.add(Expression.in("ai.id", longs));
criteria.add(Expression.eq("c.empresa.id", empresaId));
criteria.addOrder(Order.asc("c.nome"));

criteria.setProjection(Projections.distinct(p));
...

SQL gerado:
select
distinct this_.id as y0_,
this_.nome as y1_
from
...

quinta-feira, 17 de janeiro de 2008

SubQuery com criteria e projection

DetachedCriteria subQuery = DetachedCriteria.forClass(Moeda.class, "subMoeda");
ProjectionList p = Projections.projectionList().create();

p.add(Projections.property("subMoeda.observacao"), "observacao");
subQuery.setProjection(p);

subQuery.add(Expression.eq("subMoeda.id", 7L));

Criteria criteria = getSession().createCriteria(Moeda.class, "moeda");

ProjectionList p2 = Projections.projectionList().create();

p2.add(Projections.property("moeda.observacao"), "observacao");
p2.add(Projections.property("moeda.nome"), "nome");
p2.add(Projections.property("moeda.cifra"), "cifra");

criteria.setProjection(p2);
criteria.add(Property.forName("moeda.nome").eq(subQuery));

criteria.setResultTransformer(new AliasToBeanResultTransformer(Moeda.class));
Collection lista = criteria.list();


CONSOLE:

select
this_.observacao as y0_,
this_.nome as y1_,
this_.cifra as y2_
from
Moeda this_
where
this_.nome = (
select
this0__.observacao as y0_
from
Moeda this0__
where
this0__.id=?
)