JSF 2.0, Session Beans and JPA using Scala

I’ve been working on using Scala(version 2.7.7) to write Java EE 6 applications on the Glassfish V3 server. Recently I wrote a CRUD application using JSF 2.0, JPA and Session Beans. I used Eclipse for development using the Scala plugin for Eclipse. Those who are aware of the JSF 2.0 specification already know ManagedBeans are out of style! Use Named beans instead. I wrote my ManagedBean and SessionBean in the same class.

Lets look at how the class is defined.

import scala.reflect._
import java.util.ArrayList;
import java.util.{List => JList}
import javax.inject.Named
import javax.ejb.LocalBean
import javax.enterprise.context.SessionScoped
import javax.faces.model.DataModel
import javax.faces.model.ListDataModel;
import javax.ejb.Stateful;
import javax.persistence._
import java.io.Serializable

@Named{val value="userController"}
@SessionScoped
@Stateful
@LocalBean
class UserController extends Serializable {

For Named Beans to work, they need implement the Serializable interface in Java, so while writing the same in Scala, we “extend” it. The @LocalBean annotation is unique to the Scala implementation. Without this annotation, the session bean exposes a local business interface(ScalaObject in this case) as its client instead of UserController. Refer to this post on java.net.

Once the class is up, lets look at how to get an instance of the EntityManager.

@PersistenceContext private[this] var em: EntityManager = _

To query a table:

@SuppressWarnings(Array("unchecked")) def load:JList[User]= {
val q:Query = em.createQuery("SELECT x FROM User x");
var results = q.getResultList().asInstanceOf[JList[User]]
results;
}

Notice the “JList”. Its the java.util.List being renamed as JList, refer to the import statements above: import java.util.{List => JList}
without which there’s some sort of conflict. I dont remember the exact reason( I figured it out a while ago and dont remember now ).

As for the create(), edit() and delete() methods:

def create(user:User):Unit = {
em.persist(user);
}


def edit():java.lang.String = {
em.merge(current.get);
items = null;

"List";
}


def destroy(user:User):java.lang.String = {
current = Some(user);
em.remove(em.merge(user));
items = null;

"List";
}

These methods are as simple as calling the persist, merge or remove methods using the EntityManager object. That’s it!

Advertisements