¿Cómo se selecciona una columna usando Hibernate?


Me gustaría seleccionar una sola columna en lugar de un objeto completo, usando Hibernar. Hasta ahora tengo esto:

 List<String> firstname = null;

 firstname = getSession().createCriteria(People.class).list();

Mi problema es que el código anterior devuelve toda la tabla People como un objeto en lugar de solo "firstname". No estoy seguro de cómo especificar que solo devuelva "firstname" en lugar de todo el objeto.

Author: ThreaT, 2012-05-18

3 answers

Puede establecer la Proyección para esto como:

.setProjection(Projections.property("firstname"))

Con esto solo puede obtener el nombre a cambio.

He encontrado otro enlace en stack con el mismo escenario. Espero que esto también ayude ¿Cómo usar criterios de hibernación para devolver solo un elemento de un objeto en lugar de todo el objeto?

 43
Author: rizzz86,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:46:37

Si necesita consultar 2 o más columnas y obtener los valores de la consulta, esta es la manera de hacerlo:

....
crit.setProjection(Projections.property("firstname"));
crit.setProjection(Projections.property("lastname"));

List result = crit.list();

...

for (Iterator it = result.iterator(); it.hasNext(); ) {
    Object[] myResult = (Object[]) it.next();
    String firstname = (String) myResult[0];
    String lastname = (String) myResult[1];

    ....
}
 7
Author: Thai Tran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-11-21 03:10:19

Puede usar ProjectionList si desea una proyección base de condición por ejemplo,

  ProjectionList prjection = Projections.projectionList();
if(abc){
    prjection.add(Projections.property("firstname"));
}
else if(xyz){
    prjection.add(Projections.property("lastname"));
}

    ........

    criteria.setProjection(prjection);
 2
Author: DDshah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-03 10:53:27