Monday, June 15, 2009

Creating A New User

Back in RPXResults.java, we've gotten our identifier and need to create a User. With JDO, that's a two-step process. First we create the User instance and populate it. Second we store that data to the datastore.

Creating the User is nothing new:


String identifier = info.getElementsByTagName("identifier").item(0).getTextContent();
User user = new User ();
user.setIdentifier(identifier);


We could search through the profile data to see if any of the various name fields were provided and use those to pass to user.setName, but I'll opt for the simple route of asking them for their name later. For now we'll leave it null.

Now for storing the User to the datastore. We need to get an instance of a PerstistenceManager from the factory:


PersistenceManager pm = PMF.get().getPersistenceManager();


Then we call makePersistent:


try
{
  pm.makePersistent(user);
}
finally
{
  pm.close();
}


The odd try/finally usage is worth a comment. There's no catch block needed, because there are no checked exceptions thrown by makePersistent. So why a try block in the first place? I'd guess it's because makePersistent can throw some runtime exceptions, and the finally block is a way to ensure the manager gets closed even if a runtime exception is thrown.

That saves the User to the datastore. In the next post we'll add in querying the datastore to see if the user already exists, so we only create the user if this is their first time using our application.

No comments:

Post a Comment