Question

I have a method which return a Query:

def list:Query[User] = from(users)(u => where(u.age>20) select(u))

Now I want to count the list, but this method:

list.count(_ => true)

will get and loop all elements in the list.

I want to find a solution to make a "select count" statement from the Query[User], but not found yet.

Or I have to write another method for count:

def countList: Long = from(users)(u => where(u.age>20) compute(count))

Which is not what I want.

Was it helpful?

Solution

Try to compose the two queries:

from(list)(_ => compute(count))

OTHER TIPS

In such cases it might make sense to make a common query builder, so you can keep the condition logic at a single place. It's handy when you are paging a query result set.

def queryBuilder[T](action: User => WhereState[Conditioned] => QueryYield[T]) : Query[T] = from(users)(u => action(u)(where(u.age>20)))

def countQuery = queryBuilder(u => w => w.compute(count))

def selectQuery = queryBuilder(u => w => w.select(u))

Here is an example of DAO object:

def countByJobPostingId(jobPostingId: Int): Long = {
  inTransaction {
    val q = from(table)(t =>
      where(t.jobPostingId === jobPostingId)
        compute count
    )

    LOG.debug(q.statement)

    q.head.measures
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top