I want to make a criteria query that has the same behaviour as the following SQL query:
SELECT Count(*)
FROM Datagathering_respuestas, Datagathering
WHERE Datagathering.document = 4 AND Datagathering.id_datagathering = datagathering_respuestas.id_datagathering
GROUP BY respuesta;
it is all around the following class:
public class DataGathering {
private int id;
private Usuario user;
private Date fecha;
private int individual;
private DataDocument document;
private List<String> respuestas;
and it’s corresponding mapping file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="pe.com.abf.pws.clases.DataGathering">
<id column="id_datagathering" name="id">
<generator class="identity"/>
</id>
<many-to-one class="pe.com.abf.pws.clases.DataDocument" name="document"/>
<many-to-one class="pe.com.abf.pws.clases.Usuario" name="user"/>
<property name="individual"/>
<property name="fecha" type="timestamp"/>
<list name="respuestas">
<key column="id_datagathering"/>
<index column="idx_respuesta"/>
<element column="respuesta" length="4000" type="string"/>
</list>
</class>
</hibernate-mapping>
my main problem here is that the grouping property “respuestas” is defined as a list of element of type string and doesn’t have it’s own class. In SQL it’s easy to just reference to the corresponding table, but in Criteria, I have no idea how to reference to the elements to group by them. I have managed to get this query:
Criteria c = s.createCriteria(DataGathering.class);
c.add(Restrictions.eq("document.id", id));
c.createCriteria("respuestas","resp");
c.setProjection(Projections.projectionList().add(Projections.rowCount()));
which has the same behaviour as the above SQL query but without the group by element, so I think I am near. The problem is again that I don’t know how to refer to the values inside “respuestas”.
Any Idea how I can complete my query? any help will be highly appreciated.
I managed to do this by doing the following:
The trick is that Criteria uses the key
"elements"to refer to a plain element collection. Then, giving the projections alias that match with the properties of an special class you can easily make a list of that class to use it on reports.Thanks to anyone who tried to help