如何在hibernate中编写count(*)查询

50pmv0ei  于 2023-05-29  发布在  其他
关注(0)|答案(3)|浏览(160)

我想在 Hibernate 中执行下面的查询?
select count(*) from login where emailid='something' and password='something'

olqngx59

olqngx591#

假设您的login表由LoginClass类Map,其中包含emailidpassword示例变量。然后你将执行类似于:

Query query = session.createQuery(
        "select count(*) from LoginClass login where login.emailid=:email and login.password=:password");
query.setString("email", "something");
query.setString("password", "password");
Long count = (Long)query.uniqueResult();

它应该在count中返回您要查找的结果。你只需要调整你的类和参数的名字。

eh57zj3b

eh57zj3b2#

结果返回BigDecimal,您需要将其从Bigdecimal(java.math.BigDecimal)转换为Long,以便没有错误,解决方案如下:

Query query = session.createSQLQuery(
        "select count(*) from login where login.emailid=:email and login.password=:password");
query.setString("email", "something");
query.setString("password", "password");
Long count = ((BigDecimal) query.uniqueResult()).longValue();
4xy9mtcn

4xy9mtcn3#

你可以在Hibernate 6中这样查询:

public int getCount() {
    int result = 0;
    try {
        session.beginTransaction();

        result = session.createNativeQuery("select count(*) from user", Integer.class).uniqueResult();

        session.getTransaction().commit();

    } catch (Exception exception) {
        exception.printStackTrace();
    }

    return result;
}

相关问题