Warning: Trying to access array offset on value of type bool in /home/www/blog/wp-content/themes/catch-box/functions.php on line 1079

Wrapping JPA Queries

I love the “pattern” used in this post (which I got from here).

Working with JPA queries I tried to follow the same pattern. In a REST resource I needed to query for one entity and change the location attribute.

[UPDATE] This is mostly realized here [UPDATE]

The code that visually separates the query from business looks like this now:

oneEntity {
  user: User =>
   val loc = user.getUsersLocation
} withQuery ("select u from User u where u.name like ?1",

And the resource base class code providing that:

  protected def oneEntity[A, T](body: (T) => A): DoWithQuery[A, T] =
       new DoWithQuery[A, T](body)

  protected class DoWithQuery[A, T](body: (T) => A) {
    def withQuery(query: String, param: AnyRef*): A = {
      val q = createQuery(query)

      var i: Int = 1
      param.foreach {
        x =>
          q.setParameter(i, x)
          i += 1

      val res = q.getResultList
      if (res.isEmpty) throw new WebApplicationException(404)
      val user = res.get(0).asInstanceOf[T]