1057 words

Database Connection using JPA

Working with the Java Persistence API (JPA) consists of using the following interfaces:

Overview

A connection to a database is represented by an EntityManagerjavax.persistence.EntityManagerJPA interfaceInterface used to interact with the persistence context.
See JavaDoc Reference Page...
instance, which also provides functionality for performing operations on a database. Many applications require multiple database connections during their lifetime. For instance, in a web application it is common to establish a separate database connection, using a separate EntityManager instance, for every HTTP request.

The main role of an EntityManagerFactoryjavax.persistence.EntityManagerFactoryJPA interfaceInterface used to interact with the entity manager factory for the persistence unit.
See JavaDoc Reference Page...
instance is to support instantiation of EntityManagerjavax.persistence.EntityManagerJPA interfaceInterface used to interact with the persistence context.
See JavaDoc Reference Page...
instances. An EntityManagerFactory is constructed for a specific database, and by managing resources efficiently (e.g. a pool of sockets), provides an efficient way to construct multiple EntityManager instances for that database. The instantiation of the EntityManagerFactory itself might be less efficient, but it is a one time operation. Once constructed, it can serve the entire application.

Operations that modify the content of a database require active transactions. Transactions are managed by an EntityTransactionjavax.persistence.EntityTransactionJPA interfaceInterface used to control transactions on resource-local entity managers.
See JavaDoc Reference Page...
instance obtained from the EntityManager.

An EntityManager instance also functions as a factory for Queryjavax.persistence.QueryJPA interfaceInterface used to control query execution.
See JavaDoc Reference Page...
instances, which are needed for executing queries on the database.

Every JPA implementation defines classes that implement these interfaces. When you use ObjectDB you work with instances of ObjectDB classes that implement these interfaces, and because standard JPA interfaces are used your application is portable.

EntityManagerFactory

An EntityManagerFactoryjavax.persistence.EntityManagerFactoryJPA interfaceInterface used to interact with the entity manager factory for the persistence unit.
See JavaDoc Reference Page...
instance is obtained by using a static factory method of the JPA bootstrap class, Persistencejavax.persistence.PersistenceJPA classBootstrap class that is used to obtain an EntityManagerFactory in Java SE environments.
See JavaDoc Reference Page...
:

Another form of the createEntityManagerFactorycreateEntityManagerFactory(persistenceUnitName, properties)Persistence's static methodCreate and return an EntityManagerFactory for the named persistence unit using the given properties.
See JavaDoc Reference Page...
method takes a map of persistence unit properties as a second parameter:

The EntityManagerFactoryjavax.persistence.EntityManagerFactoryJPA interfaceInterface used to interact with the entity manager factory for the persistence unit.
See JavaDoc Reference Page...
instance, when constructed, opens the database. If the database does not yet exist a new database file is created.

When the application is finished using the EntityManagerFactory it has to be closed:

Closing the EntityManagerFactory closes the database file.

Connection URL

The createEntityManagerFactorycreateEntityManagerFactory(persistenceUnitName)Persistence's static methodCreate and return an EntityManagerFactory for the named persistence unit.
See JavaDoc Reference Page...
method takes as an argument a name of a persistence unit.
As an extension, ObjectDB enables specifying a database url (or path) directly, bypassing the need for a persistence unit. Any string that starts with objectdb: or ends with .odb or .objectdb is considered by ObjectDB to be a database url rather than as a persistence unit name.

To use ObjectDB embedded directly in your application (embedded mode), an absolute path or a relative path of a local database file has to be specified (e.g. "my.odb"). Specifying the objectdb: protocol as a prefix (e.g. "objectdb:my.odb") is optional if the database file name extension is odb or objectdb and required for other file name extensions (e.g. "objectdb:my-db.tmp").

To use client server mode, a url in the format objectdb://host:port/path has to be specified.
In this case, an ObjectDB Database Server is expected to be running on a machine named host (could be domain name or IP address) and listening on the specified port (the default is 6136 when not specified). The path indicates the location of the database file on the server, relative to the server data root path.

Connection URL Parameters

The following parameters are supported as part of an ObjectDB connection url:

  • user - for specifying a username in client server mode.
  • password - for specifying a user password in client server mode.
  • drop - for deleting any existing database content (useful for tests).

To connect to an ObjectDB server registered username and password have to be specified:

This is equivalent to specifying a username and a password in the persistence unit or in a map of properties (as demonstrated above).

To obtain a connection to an empty database (discarding existing content if any) the drop parameter has to be specified:

Getting an empty clean database easily is very useful in tests. However, to avoid the risk of losing data - the drop parameter is ignored unless the database file name extension indicates that it is a temporary database. By default, the tmp and temp file name extensions represent temporary databases that can be dropped, but this can be configured.

EntityManager

An EntityManagerjavax.persistence.EntityManagerJPA interfaceInterface used to interact with the persistence context.
See JavaDoc Reference Page...
instance may represent either a remote connection to a remote database server (in client-server mode) or a local connection to a local database file (in embedded mode). The functionality in both cases is the same. Given an EntityManagerFactoryjavax.persistence.EntityManagerFactoryJPA interfaceInterface used to interact with the entity manager factory for the persistence unit.
See JavaDoc Reference Page...
emf
, a short term connection to the database might have the following form:

The EntityManager instance is obtained from the owning EntityManagerFactory instance. Calling the closeclose()EntityManager's methodClose an application-managed entity manager.
See JavaDoc Reference Page...
method is essential to release resources (such as a socket in client-server mode) back to the owning EntityManagerFactory.

EntityManagerFactory defines another method for instantiation of EntityManager that, like the factory, takes a map of properties as an argument. This form is useful when a user name and a password other than the EntityManagerFactory's default user name and password have to specified:

EntityTransaction

Operations that affect the content of the database (store, update, delete) must be performed within an active transaction. The EntityTransactionjavax.persistence.EntityTransactionJPA interfaceInterface used to control transactions on resource-local entity managers.
See JavaDoc Reference Page...
interface represents and manages database transactions. Every EntityManagerjavax.persistence.EntityManagerJPA interfaceInterface used to interact with the persistence context.
See JavaDoc Reference Page...
holds a single attached EntityTransaction instance that is available via the getTransactiongetTransaction()EntityManager's methodReturn the resource-level EntityTransaction object.
See JavaDoc Reference Page...
method:

A transaction is started by a call to beginbegin()EntityTransaction's methodStart a resource transaction.
See JavaDoc Reference Page...
and ended by a call to either commitcommit()EntityTransaction's methodCommit the current resource transaction, writing any unflushed changes to the database.
See JavaDoc Reference Page...
or rollbackrollback()EntityTransaction's methodRoll back the current resource transaction.
See JavaDoc Reference Page...
. All the operations on the database within these boundaries are associated with that transaction and are kept in memory until the transaction is ended. If the transaction is ended with a rollback, all the modifications to the database are discarded. However, by default, the in-memory instance of the managed entity is not affected by the rollback and is not returned to its pre-modified state.

Ending a transaction with a commit propagates all the modifications physically to the database. If for any reason a commit fails, the transaction is rolled back automatically (including rolling back modifications that have already been propagated to the database prior to the failure) and a RollbackExceptionjavax.persistence.RollbackExceptionJPA exceptionThrown by the persistence provider when EntityTransaction.commit() fails.
See JavaDoc Reference Page...
is thrown.


This documentation explains how to use JPA in the context of the ObjectDB Object Database but mostly relevant
also for ORM JPA implementations, such as Hibernate (and HQL), EclipseLink, TopLink, OpenJPA and DataNucleus.
ObjectDB is not an ORM JPA implementation but an Object Database (ODBMS) for Java with built in JPA 2 support.