TJDO Tutorial: Step 3

Step 1 | Step 2 | Step 3 | Step 4 | Step 5

Step 3: Persist a Person within a Transaction

Now that we have a PersistenceCapable class, we can persist it. This can be accomplished in a number of ways, one of which is by simply calling PersistenceManager.makePersistent(Object).

We need to retrieve a PersistenceManager from a PersistenceManagerFactory. One way to get a PersistenceManagerFactory is by calling JDOHelper.getPersistenceManagerFactory(Properties). The properties that you use need to include the database connection information (database URL, JDBC driver, database user name, and password), as well as the class name of PersistenceManagerFactory implementation (for TJDO, this is com.triactive.jdo.PersistenceManagerFactoryImpl).

Here is an example that demonstrates obtaining a PersistenceManager and making a Person persistent. The full source code is available here.

package test;

public class PersonPersister
  public static void main(String[] args)
     * Define a PersistenceManagerFactory.  The autoCreateTables property is
     * specific to TJDO and causes any missing database tables to be created
     * automatically.
    Properties props = new Properties();
    props.setProperty("javax.jdo.PersistenceManagerFactoryClass", "com.triactive.jdo.PersistenceManagerFactoryImpl");
    props.setProperty("javax.jdo.option.ConnectionDriverName",    "org.apache.derby.jdbc.EmbeddedDriver");
    props.setProperty("javax.jdo.option.ConnectionURL",           "jdbc:derby:myTestDatabase;create=true");
    props.setProperty("javax.jdo.option.ConnectionUserName",      "");
    props.setProperty("javax.jdo.option.ConnectionPassword",      "");
    props.setProperty("com.triactive.jdo.autoCreateTables",       "true");

    PersistenceManagerFactory pmf = JDOHelper.getPersistenceManagerFactory(props);
    PersistenceManager pm = pmf.getPersistenceManager();

     * Get the transaction management interface for this PersistenceManager.
     * The transaction API allows manual database commits and rollbacks.  Many
     * PersistenceManager methods throw an exception if a transaction is not
     * active.
    Transaction tx = pm.currentTransaction();

      tx.begin();   /* Begin a transaction. */

      /* Create a Person object and make it persistent. */
      Person person = new Person("John", "Doe", 34);

      tx.commit();  /* Commit the transaction. */
       * In the finally block we make sure that all resources have been cleaned
       * up.  Once a transaction is begun either commit() or rollback() must be
       * called exactly once.  If the transaction is still active here then commit()
       * was not called due to an exception, so we rollback.
      if (tx.isActive())

       * Calling pm.close() promptly releases any resources used by the PM.  TJDO
       * logs a warning if you fail to close a PM before it is garbage collected.