Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

There are a number of style choices for using the above bean, specifically around the creation of the Callable object you pass in, and it all really depends on what looks nice to you.

In the examples below, the Movies bean being tested is simply a thin layer around JPA that allows us to use enforce various transaction semantics.

Code Block

import javax.ejb.Stateful;
import javax.ejb.TransactionAttribute;
import static javax.ejb.TransactionAttributeType.MANDATORY;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.Query;
import java.util.List;

@Stateful(name = "Movies")
@TransactionAttribute(MANDATORY)
public class MoviesImpl implements Movies {

    @PersistenceContext(unitName = "movie-unit", type = PersistenceContextType.TRANSACTION)
    private EntityManager entityManager;

    public void addMovie(Movie movie) throws Exception {
        entityManager.persist(movie);
    }

    public void deleteMovie(Movie movie) throws Exception {
        entityManager.remove(movie);
    }

    public List<Movie> getMovies() throws Exception {
        Query query = entityManager.createQuery("SELECT m from Movie as m");
        return query.getResultList();
    }
}

Test code below.

Pure inlined

Code Block
public class MoviesTest extends TestCase {
    private Context context;

    protected void setUp() throws Exception {
        // initialize jndi context as usual
    }

    public void test() throws Exception {
        Caller transactionBean = (Caller) context.lookup("TransactionBeanLocal");

        transactionBean.call(new Callable() {
            public Object call() throws Exception {
                Movies movies = (Movies) context.lookup("MoviesLocal");

                movies.addMovie(new Movie("Quentin Tarantino", "Reservoir Dogs", 1992));
                movies.addMovie(new Movie("Joel Coen", "Fargo", 1996));
                movies.addMovie(new Movie("Joel Coen", "The Big Lebowski", 1998));

                List<Movie> list = movies.getMovies();
                assertEquals("List.size()", 3, list.size());

                for (Movie movie : list) {
                    movies.deleteMovie(movie);
                }

                assertEquals("Movies.getMovies()", 0, movies.getMovies().size());

                return null;
            }
        });
    }
}

...