Skip to content

JPA 101

(This is too good of an article to not re-post here just to have it)
JPA 101

If there’s one thing you have to understand to successfully use JPA (Java Persistence API) it’s the concept of a Cache. Almost everything boils down to the Cache at one point or another. Unfortunately the Cache is an internal thing and not exposed via the JPA API classes, so it not easy to touch or feel from a coding perspective.

Here’s a quick cheat sheet of the JPA world:

A Cache is a copy of data, copy meaning pulled from but living outside the database.
Flushing a Cache is the act of putting modified data back into the database.
A PersistenceContext is essentially a Cache. It also tends to have it’s own non-shared database connection.
An EntityManager represents a PersistenceContext (and therefore a Cache)
An EntityManagerFactory creates an EntityManager (and therefore a PersistenceContext/Cache)
Comparing RESOURCE_LOCAL and JTA persistence contexts

With you are responsible for EntityManager (PersistenceContext/Cache) creating and tracking…

You must use the EntityManagerFactory to get an EntityManager
The resulting EntityManager instance is a PersistenceContext/Cache
An EntityManagerFactory can be injected via the @PersistenceUnit annotation only (not @PersistenceContext)
You are not allowed to use @PersistenceContext to refer to a unit of type RESOURCE_LOCAL
You must use the EntityTransaction API to begin/commit around every call to your EntityManger
Calling entityManagerFactory.createEntityManager() twice results in two separate EntityManager instances and therefor two separate PersistenceContexts/Caches.
It is almost never a good idea to have more than one instance of an EntityManager in use (don’t create a second one unless you’ve destroyed the first)
With the container will do EntityManager (PersistenceContext/Cache) creating and tracking…

You cannot use the EntityManagerFactory to get an EntityManager
You can only get an EntityManager supplied by the container
An EntityManager can be injected via the @PersistenceContext annotation only (not @PersistenceUnit)
You are not allowed to use @PersistenceUnit to refer to a unit of type JTA
The EntityManager given by the container is a reference to the PersistenceContext/Cache associated with a JTA Transaction.
If no JTA transaction is in progress, the EntityManager cannot be used because there is no PersistenceContext/Cache.
Everyone with an EntityManager reference to the same unit in the same transaction will automatically have a reference to the same PersistenceContext/Cache
The PersistenceContext/Cache is flushed and cleared at JTA commit time

Cache == PersistenceContext

The concept of a database cache is an extremely important concept to be aware of. Without a copy of the data in memory (i.e. a cache) when you call account.getBalance() the persistence provider would have to go read the value from the database. Calling account.getBalance() several times would cause several trips to the database. This would obviously be a big waste of resources. The other side of having a cache is that when you call account.setBalance(5000) it also doesn’t hit the database (usually). When the cache is “flushed” the data in it is sent to the database via as many SQL updates, inserts and deletes as are required. That is the basics of java persistence of any kind all wrapped in a nutshell. If you can understand that, you’re good to go in nearly any persistence technology java has to offer.

Complications can arise when there is more than one PersistenceContext/Cache relating the same data in the same transaction. In any given transaction you want exactly one PersistenceContext/Cache for a given set of data. Using a JTA unit with an EntityManager created by the container will always guarantee that this is the case. With a RESOURCE_LOCAL unit and an EntityManagerFactory you should create and use exactly one EntityManager instance in your transaction to ensure there is only one active PersistenceContext/Cache for the given set of data active against the current transaction.

Caches and Detaching

Detaching is the concept of a persistent object leaving the PersistenceContext/Cache. Leaving means that any updates made to the object are not reflected in the PersistenceContext/Cache. An object will become Detached if it somehow lives longer or is used outside the scope of the PersistenceContext/Cache.

For a JTA unit, the PersistenceContext/Cache will live as long as the transaction does. When a transaction completes (commits or rollsback) all objects that were in the PersistenceContext/Cache are Detached. You can still use them, but they are no longer associated with a PersistenceContext/Cache and modifications on them will not be reflected in a PersistenceContext/Cache and therefore not the database either.

Serializing objects that are currently in a PersistenceContext/Cache will also cause them to Detach.

In some cases objects or collections of objects that become Detached may not have all the data you need. This can be because of lazy loading. With lazy loading, data isn’t pulled from the database and into the PersistenceContext/Cache until it is requested in code. In many cases the Collections of persistent objects returned from an javax.persistence.Query.getResultList() call are completely empty until you iterate over them. A side effect of this is that if the Collection becomes Detached before it’s been fully read it will be permanently empty and of no use and calling methods on the Detached Collection can cause strange errors and exceptions to be thrown. If you wish to Detach a Collection of persistent objects it is always a good idea to iterate over the Collection at least once.

You cannot call EntityManager.persist() or EntityManager.remove() on a Detached object.

Calling EntityManager.merge() will re-attach a Detached object.

Valid RESOURCE_LOCAL Unit usage

Servlets and EJBs can use RESOURCE_LOCAL persistence units through the EntityManagerFactory as follows:


And referenced as follows

import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceUnit;

public class MyEjbOrServlet … {

private EntityManagerFactory factory;

// Proper exception handling left out for simplicity
public void ejbMethodOrServletServiceMethod() throws Exception {
EntityManager entityManager = factory.createEntityManager();

EntityTransaction entityTransaction = entityManager.getTransaction();


Account account = entityManager.find(Account.class, 12345);



Valid JTA Unit usage

EJBs can use JTA persistence units through the EntityManager as follows:


And referenced as follows

import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.ejb.TransactionAttributeType;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

public class MyEjb implements MyEjbInterface {

@PersistenceContext(unitName = “Tutorial”)
private EntityManager entityManager;

// Proper exception handling left out for simplicity
public void ejbMethod() throws Exception {

Account account = entityManager.find(Account.class, 12345);



TDD – Using EasyMock to test your Spring Controllers

While this wasn’t necessarily TDD (because I had the controller stubbed out first), it illustrates how you can mock out the HttpRequest, a Service implementation that doesn’t exist, and a logged in user that was never logged in.  Which covers just about everything you would expect to need when running a web MVC app on the server.

import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.createMock;
import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;

public class LocationControllerTest {

private LocationController controller;
private ILocationService locationService;
private UserProfile userProfile;

public void setUp() {
userProfile = createMock(UserProfile.class);
controller = new LocationController() {
@Override public UserProfile getProfile(HttpServletRequest request) {
return userProfile; }
locationService = createMock(ILocationService.class);

public void findLocation() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
SearchForm form = new SearchForm();
BindingResult errors = new BindException(form, “searchForm”);

//given (record expectations for later playback)

ModelAndView mav = controller.locationLookup(request, form, errors);

Listlocations =

//happy path was achieved
assertEquals(“display-locations”, mav.getViewName());
assertEquals(2, locations.size());

* Mock out Profile calls that are called on a logged in user.
protected void populateMockProfile() {
Name name = new Name(“John”, “Smith”);
UserInfo userInfo = sampleUserInfo();

* Setup a member that is retrieved via profile data.
* @return
protected UserInfo sampleUserInfo() {
UserInfo userInfo = new UserInfo();
return userInfo;
protected List sampleLocations() {
List locations = ArrayList();
locations.add(new Location());
locations.add(new Location());
return locations;
protected AccountSummary sampleAccountSummary() {
AccountSummary account = new AccountSummary();
return account;

Tomcat7 and openEJB – finally a lightweight container to go along with a lightweight EJB/WebService implementation

Since I love Tomcat over the bulk of Weblogic anyday, I was also looking for another way to annotate a remote object the simplest way possible, but also have it available as a Web Service. Tomcat to the rescue….
First of all, here is where I started a few weeks ago after getting frustrated with all the Weblogic annotations and seemingly unnecessary technical overhead that along with transforming remote objects into Web Services while keeping the deployable nature of an EJB:

Here’s a small example I modified that will get deployed as an EJB, but also is recognized as a Web Service:

portName = “LocationPort”,
serviceName = “LocationService”,
targetNamespace = “http://localhost/wsdl”,
endpointInterface = “”)
public class LocationService implements LocationWs {
public String getLocation(int lat, int long) {
return “location”;

@WebService(targetNamespace = “http://localhost/wsdl”)
public interface LocationWs {
public String getLocation(int lat, int long);

Now….get access as a Web Service:
Service locationService = Service.create(
new URL(“”),
new QName(“http://localhost/wsdl”, “LocationService”));
LocationWs location = locationService.getPort(LocationWs.class);
location.getLocation(45.22233, -93.33435);

And now as a remote EJB:
Properties p = new Properties();
p.put(“java.naming.factory.initial”, “org.apache.openejb.client.RemoteInitialContextFactory”);
p.put(Context.PROVIDER_URL, “ejbd://”);

LocationWs myCalc = (LocationWs)context.lookup(“LocationRemote”);
location.getLocation(45.22233, -93.33435);

You can also use SoapUI to test that it’s deployed as a Web Service – that’s a very handy tool….

Spring MVC server-side validation

Handling server-side validation in Spring MVC


@RequestMapping(method = RequestMethod.POST)
public ModelAndView handleRequest(HttpServletRequest request,
@ModelAttribute(value="myForm") MyForm form,
BindingResult result) throws Exception {
MyFormValidator validator = new MyFormValidator();
validator.validate(form, result);
if (result.hasErrors()) {
ModelAndView mav = new ModelAndView("showSummaryPage");
return mav;


Spring MVC wizard functionality without Web Forms

After investigating Spring Web Forms as a way to retrofit wizard functionality into an existing web application, I wasn’t real crazy about all the configuration that was required in my already annotated web application, so I quickly abandoned bringing in another new web technology that didn’t quite do the job I wanted it to.

I simply needed split out my existing multi-request controller methods into two separate (GET and POST) methods so my GET method was only responsible for retrieving an already populated form from the session and going back to the previous page, while the POST method only handled the post from the previous form, any validation, and the building of the next form and page. In the end, I made the basic rule of using POSTS to go forward to any page, and GETS to go back.

Read more…

Removing invalid dates within jQuery datepicker

The task…initialize jquery datepicker with start, end dates, and use ajax to help populate closed and/or holiday dates during that date range. Oh yeah, and also use the built-in jquery validation to validate the form before we can submit.

We first start out here by grabbing the start/end dates from hidden fields in the page…

var startDate = $(“#startDateHidden”).val();
var endDate = $(“#endDateHidden”).val();
var validationText = $(“#datepickerValidationText”).val();

changeMonth: true,
changeYear: true,
minDate: new Date(startDate),
maxDate: new Date(endDate),
onSelect: function(dateText, inst)
{ handleDateSelection(dateText); },
closeOnSelect: true,
beforeShowDay: getClosedDates

Read more…

Game Development Basics

As found on the Blackberry website, all games will follow the same simple structure, but will vary depending on game complexity, the game platform, and the game type.
Most games will require objects to move on their own or by user input, and for the gaming screen to be constantly changing.  In order to accomplish this, your game will need to multi task very well – this is done by using multiple threads that will handle the looping, painting, and updating of the graphics.
The loop will consist of processing some user input, updating the screen, and then rendering it.  If you think of the screen as the game world, you must be constantly updating and drawing your game world to account for user input as well as the artificial intelligence that controls other objects on the screen that appear to think for themselves.

If you’re not already familiar with the Java Graphics object, you’ll need to be.  You’ll also need to understand how the graphics are drawn on the coordinate system with the X,Y coordinates.  Not exactly rocket science, but you’ll need to know the basics in order for screen placement and for moving the objects around the screen.
Another important aspect to of game development of identifying when two graphics objects intersect each other.  This will be done by knowing the coordinates of the objects on the screen, and knowing the dimensions of the objects.

Here’s some link to get started until we add some code samples:


Get every new post delivered to your Inbox.