Persistent Objects for Java

The most basic example assumes a table representing a person. It has two data columns, `firstName' and `lastName', both of type string. Additionally, it has an integer primary key column (implicitly named `id') that is fed from a database sequence `Seq_Person'.

Class definition in the meta-data file:

    <class name="Person">
      <idField sequenceName="Seq_Person" />
      <field name="firstName" schemaName="first_name">
	<string size="128" />
      </field>
      <field name="lastName" schemaName="last_name">
	<string size="128" />
      </field>
    </class>
        

The table definition for our RDBMS system (PostgreSQL in this case) looks like this:

    CREATE SEQUENCE Seq_Person;
    CREATE TABLE Person (
      id INTEGER CONSTRAINT nn_Person_id NOT NULL,
	CONSTRAINT pk_Person PRIMARY KEY(id),
      first_name VARCHAR(64) CONSTRAINT nn_Person_first_name NOT NULL,
      last_name VARCHAR(64) CONSTRAINT nn_Person_last_name NOT NULL
    );
        

Now to application's view on this table and its rows. First, create our object container `cnt' on top of the database connection `conn' and start a transaction:

    cnt = new PostgreSQLContainer(conn);
    cnt.beginTransaction();
        

Add an object to the database table `Person':

    person = new Person("Michael", "van Acken");
    cnt.makePersistent(person);
    person.store();
        

Retrieve all `Person' objects from the corresponding table:

    q = cnt.newQuery();
    q.addTableExpr(Person.cdeclPerson, false);
    res = q.execute();
        

At this place, `res[0][0]' holds the first object, `res[1][0]' the second, and so on. To retrieve a subset of all persons matching a particular pattern, one needs to add a filter predicate to the query:

    q = cnt.newQuery();
    q.addTableExpr(Person.cdeclPerson, false);
    q.addConj(Predicate.like(new Member(0, Person.attrFirstName),
                             new Literal("Mich%")));
    res = q.execute();
        

This returns all `Person' objects whose first name begins with `Mich'.

Removing a table row:

    person.delete();
    person.store();
        

And finally, closing the transaction:

    cnt.commitTransaction();