Classy Tools

People and Pets V2

People and Pets V2 adds a "quote" field to both sample entity classes PetData and PeopleData. The application's database file is also used by version 1, so if will need to be updated if version 1 has run previously. The update occurs automatically the first time version 2 starts.

Jpalite people-and-pets-example Java project version 2 application is launched from PeopleAndPetsMain in package au.com.cybersearch2.pp.v2. Associated resources are in "src/main/resources/v2" project folder.

Persistence Unit Configuration

The persistence units of version 2 differ from those of version 1 in three ways

  1. The "databaseVersion" setting is updated to "2"
  2. A new ""upgradeFilename" setting is added
  3. A new "openHelperClass" setting is added

The upgrade file adds the quote column and updates the database version to 2. The open helper adds 2 records after the database is created and add quotes to the existing records when updated to version 2.

Run Version 2

Run PeopleAndPetsMain as a Java application, and you will see console output starting with info and warning level log messages from database set up operations and then a play back of an application activity recorder. The application performs various actions involving records of both persistence units to simulate typical record create, read and delete operations. Note that new database records include a quote. For example

[0] = Misha: id=1: "Once more into the breach"
[1] = Buffy: id=2: "All that glisters is not gold"

Test class PP_UpdateTest runs the Version 1 application, and then runs Version 2 twice, once to automatically upgrade the database to Version 2, the second time to test the upgrade persisted successfully. You will see on the console that the version 1 records are updated to include a quote when the database update to version 2 occurs.

Database Open Handlers

Handlers deal with three significant open database events

  1. New database created
  2. Older version database opened
  3. Newer version database opened

Built-in handlers can optionally perform SQL commands in files identified in persistence.xml. For a new database, there is a file to edit the schema and another to populate the database with records. In the newer version case, the database tables can be dropped followed by the new database handlers being executed. This is how people-and-pets version 1 is configured.

A custom handler can also be configured in persistence.xml which executes after the relevant built-in handler(s) and runs as a JPA persistence task. In the update case, it allows existing records to be updated to be consistent with the latest table schema.

Here is the SQL file to update people-and-pets version 2 Pets table

Pets table update