Search code examples
hibernatecountsubqueryhibernate-criteria

Hibernate Criteria and Count Column


I am trying to return an entity with a column that has the count of another table that is a one to many relation. I want to do this using hibernate criteria, not HQL.

select p.*, (select count(*) from child where child.parentid = p.id) as LEVELS
from parent p

Solution

  • Got it to work doing this. Not very dynamic but it will work.

        @Basic
        @Column(name = "LEVEL")
        @Formula(value="(SELECT count(*) FROM BadgeLevels bl WHERE bl.badgeid = this_.id)")
            public long getLevel() {
            return level;
        }