Jpalite

Foreign Collection

The OrmLite ForeignCollection sample is reworked as the Jpalite foreign-collection project. The original sample appears in the ormlite-jdbc test sources in the com.j256.ormlite.jdbc.examples.foreignCollection package. The readme text explains:

] "ORMLite supports what it calls "foreign" objects. These are fields that are other objects stored in the database." The Jpalite entity classes are adorned with Java Persistence annotations such as @Id, @Column, @OneToOne and @OneToMany. Jpalite simplifies working with foreign collections by allowing the details of the Ormlite Foreign Collection implementation to be hidden..

In the Foreign Collection main resources is the persistence.xml JPA configuration file. It defines the following persistence unit attributes:

  • name = account
  • classes Account and Order
  • database-name = account

Note the database is configured as in-memory, so the database name is not relevant unless there is a switch to an on-disk database.

Run foreign-collection as a Java Application from the ForeignCollectionMain class static main() and the expected console output is as follows.

Console output

Item number match is true
Account objects same is true
Item numbers match is true
At end is true
Number of account object orders is 3
Number of database orders is 3
Success

One to Many Association

We have an accounts table that has a one-to-many association with the orders table. We need to find which orders have been dispatched for a single account. The Account entity class has an "orders" field of type java.util.Collection annotated as @OneToMany as can be seen in the code snippet below.

Account fields

Jpalite at start up sets the "orders" field to a Ormlite foreign collection object. However, the Account class has a public getter which returns the collection as a list and not the collection itself as this could be a source of resource leaks.