cometta
cometta

Reputation: 35679

Hibernate generate count(1)

By default when do count with hibernate, it will generate count(*) , is it possible to change it so that the default become count(1) ? i do not want to use HQL to do this. I mean when using criteria.setProjection(Projections.rowCount());

Upvotes: 1

Views: 1015

Answers (2)

Brinda
Brinda

Reputation: 11

If your query has a GROUP BY, you can use the sqlGroupProjection() method on the theProjections class. It takes four arguments, the first of which is the select clause of the query. In this first argument you can define count(1) instead of count(*). For example:

Criteria criteria = sessionFactory.getCurrentSession().createCriteria(EventLog.class, "event")
                .createAlias("site", "site").setProjection(Projections.projectionList()
                        .add(Projections.sqlGroupProjection("var_val1,count(1) as count",
                                "var_val1",
                                new String[]{"var_val1", "count"},
                                new Type[]{Hibernate.STRING, Hibernate.INTEGER})))
                .add(Restrictions.ge("event.date_time", strFrom))
                .add(Restrictions.eq("site.companyID", custid))

Upvotes: 1

Igor Nikolaev
Igor Nikolaev

Reputation: 4697

You can create your custom count function by implementing StandartSQLFuction interface. Then you have to subclass dialect class you are using and register your function in constructor by using registerFunction method.

Upvotes: 1

Related Questions