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
   loc.setLatitude(eStatus.getLocation.getLatitude)
   loc.setLongitude(eStatus.getLocation.getLongitude)
   loc.setLocationType(eStatus.getLocation.getLocationType)
} withQuery ("select u from User u where u.name like ?1",
         sc.getUserPrincipal.getName)

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]
      body(user)
    }
  }

Comments are closed.