¿Cómo contamos las filas usando Hibernar?


Por ejemplo, si tenemos una tabla de Libros, ¿cómo contaríamos el número total de registros de libros con hibernación?

Author: rajadilipkolli, 2009-09-03

8 answers

Asumiendo que el nombre de la clase es Book:

return (Number) session.createCriteria("Book")
                  .setProjection(Projections.rowCount())
                  .uniqueResult();

Es al menos un Number, muy probablemente un Long.

 304
Author: Salandur,
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
2018-05-01 19:17:37

En Java normalmente necesito devolver int y usar este formulario:

int count = ((Long)getSession().createQuery("select count(*) from Book").uniqueResult()).intValue();
 100
Author: marioosh,
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
2010-11-27 08:06:09

Esto es lo que los documentos oficiales de hibernación nos dicen sobre esto:

Puede contar el número de resultados de la consulta sin devolverlos:

( (Integer) session.createQuery("select count(*) from ....").iterate().next() ).intValue()

Sin embargo, no siempre devuelve la instancia Integer, por lo que es mejor usar java.lang.Number por seguridad.

 43
Author: Antonio,
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
2016-02-23 09:27:34

Podrías intentar count(*)

Integer count = (Integer) session.createQuery("select count(*) from Books").uniqueResult();

Donde Books es el nombre de la class - no la tabla en la base de datos.

 12
Author: Jon Spokes,
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
2018-08-13 00:09:40

Long count = (Long) session.createQuery("select count(*) from Book") .uniqueResult();

 6
Author: xrcwrn,
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
2015-03-16 05:53:10

Si está utilizando Hibernación 5+, entonces la consulta se modificará como

Long count = session.createQuery("select count(1) from  Book")
                    .getSingleResult();

O si necesita TypedQuery

Long count = session.createQuery("select count(1) from  Book",Long.class)
                        .getSingleResult();
 6
Author: rajadilipkolli,
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-06-11 07:41:33

Esto funciona en Hibernación 4(Probado).

String hql="select count(*) from  Book";
Query query= getCurrentSession().createQuery(hql);
Long count=(Long) query.uniqueResult();
return count;

Donde getCurrentSession() es:

@Autowired
private SessionFactory sessionFactory;


private Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
 1
Author: LucianoDemuru,
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
2018-03-14 10:48:26

Es muy fácil, simplemente ejecute la siguiente consulta JPQL:

int count = (
(Number)
    entityManager
    .createQuery(
        "select count(b) " +
        "from Book b")
    .getSingleResult()
).intValue();

La razón por la que estamos fundiendo a Number es que algunas bases de datos devolverán Long mientras que otras devolverán BigInteger, así que por el bien de la portabilidad, es mejor fundir a Number y obtener un int o un long, dependiendo de cuántas filas se espera que se cuenten.

 1
Author: Vlad Mihalcea,
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
2018-06-27 06:11:23