DbController.scala 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. package hello
  2. import org.scalatra.ScalatraServlet
  3. import hello.model.{JdbcQuery, World, SingleResultQuery}
  4. import java.util.concurrent.ThreadLocalRandom
  5. import scala.annotation.tailrec
  6. class DbController extends ScalatraServlet with JsonSetup with DbSetup with JndiDataSourceProvider {
  7. val maxRows = 10000
  8. val query = SingleResultQuery.byID[World]("SELECT * FROM World WHERE id = ?") {
  9. rs => World(rs.getInt("id"), rs.getInt("randomNumber"))
  10. }
  11. get("/") {
  12. val count: Int = params.getAs[Int]("queries").getOrElse(1)
  13. useQuery(query) {
  14. q =>
  15. buildResultList(count, q)
  16. }
  17. }
  18. private def buildResultList[T](n: Int, q: JdbcQuery[T]): List[T] = {
  19. val first = fetchSingle(random, q)
  20. recursiveFetch(n - 1, q, first, Nil)
  21. }
  22. private def fetchSingle[T](id: Int, q: JdbcQuery[T]): T = q.execute(id).getOrElse(null.asInstanceOf[T])
  23. @tailrec
  24. private def recursiveFetch[T](n: Int, q: JdbcQuery[T], last: T, fetched: List[T]): List[T] =
  25. if (n == 0) {
  26. last :: fetched
  27. } else {
  28. recursiveFetch(n - 1, q, fetchSingle(random, q), last :: fetched)
  29. }
  30. private def random = ThreadLocalRandom.current().nextInt(maxRows) + 1
  31. }