Database Connection using JPA
Working with the Java Persistence API (JPA) consists of using the following interfaces:
This page covers the following topics:
Overview
A connection to a database is represented by an EntityManager
javax.persistence.EntityManager - JPA InterfaceInterface used to interact with the persistence context. 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 EntityManagerFactory
javax.persistence.EntityManagerFactory - JPA InterfaceInterface used to interact with the entity manager factory for the persistence unit. instance is to support instantiation of EntityManager
javax.persistence.EntityManager - JPA InterfaceInterface used to interact with the persistence context. 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 EntityTransaction
javax.persistence.EntityTransaction - JPA InterfaceInterface used to control transactions on resource-local entity managers. instance obtained from the EntityManager
.
An EntityManager
instance also functions as a factory for Query
javax.persistence.Query - JPA InterfaceInterface used to control query execution.javax.jdo.Query - JDO InterfaceThe Query
interface allows applications to obtain persistent instances, values, and aggregate data from the data store. 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 EntityManagerFactory
javax.persistence.EntityManagerFactory - JPA InterfaceInterface used to interact with the entity manager factory for the persistence unit.
instance is obtained by using a static factory method of the JPA bootstrap class, Persistencejavax.persistence.Persistence - JPA ClassBootstrap class that is used to obtain an {@link EntityManagerFactory}
in Java SE environments.
:
EntityManagerFactoryjavax.persistence.EntityManagerFactory - JPA InterfaceInterface used to interact with the entity manager factory for the persistence unit. emf = Persistencejavax.persistence.Persistence - JPA ClassBootstrap class that is used to obtain an {@link EntityManagerFactory} in Java SE environments..createEntityManagerFactoryPersistence.createEntityManagerFactory(persistenceUnitName) - JPA Static MethodCreate and return an EntityManagerFactory for the named persistence unit.("objectdb:myDbFile.odb");
Another form of the createEntityManagerFactory
Persistence.createEntityManagerFactory(persistenceUnitName,properties) - JPA Static MethodCreate and return an EntityManagerFactory for the named persistence unit using the given properties. method takes a map of persistence unit properties as a second parameter:
Map<String, String> properties = new HashMap<String, String>(); properties.put("javax.persistence.jdbc.user", "admin"); properties.put("javax.persistence.jdbc.password", "admin"); EntityManagerFactoryjavax.persistence.EntityManagerFactory - JPA InterfaceInterface used to interact with the entity manager factory for the persistence unit. emf = Persistencejavax.persistence.Persistence - JPA ClassBootstrap class that is used to obtain an {@link EntityManagerFactory} in Java SE environments..createEntityManagerFactoryPersistence.createEntityManagerFactory(persistenceUnitName,properties) - JPA Static MethodCreate and return an EntityManagerFactory for the named persistence unit using the given properties.( "objectdb://localhost:6136/myDbFile.odb", properties);
The EntityManagerFactory
javax.persistence.EntityManagerFactory - JPA InterfaceInterface used to interact with the entity manager factory for the persistence unit. 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:
emf.closeEntityManagerFactory.close() - JPA MethodClose the factory, releasing any resources that it holds.();
Closing the EntityManagerFactory
closes the database file.
Connection URL
The createEntityManagerFactory
Persistence.createEntityManagerFactory(persistenceUnitName) - JPA Static MethodCreate and return an EntityManagerFactory for the named persistence unit. 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 a domain name or an 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:
EntityManagerFactoryjavax.persistence.EntityManagerFactory - JPA InterfaceInterface used to interact with the entity manager factory for the persistence unit. emf = Persistencejavax.persistence.Persistence - JPA ClassBootstrap class that is used to obtain an {@link EntityManagerFactory} in Java SE environments..createEntityManagerFactoryPersistence.createEntityManagerFactory(persistenceUnitName) - JPA Static MethodCreate and return an EntityManagerFactory for the named persistence unit.( "objectdb://localhost/myDbFile.odb;user=admin;password=admin");
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:
EntityManagerFactoryjavax.persistence.EntityManagerFactory - JPA InterfaceInterface used to interact with the entity manager factory for the persistence unit. emf = Persistencejavax.persistence.Persistence - JPA ClassBootstrap class that is used to obtain an {@link EntityManagerFactory} in Java SE environments..createEntityManagerFactoryPersistence.createEntityManagerFactory(persistenceUnitName) - JPA Static MethodCreate and return an EntityManagerFactory for the named persistence unit.("objectdb:myDbFile.tmp;drop");
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 EntityManager
javax.persistence.EntityManager - JPA InterfaceInterface used to interact with the persistence context. 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.EntityManagerFactory - JPA InterfaceInterface used to interact with the entity manager factory
for the persistence unit. emf
, a short term connection to the database might have the following form:
EntityManagerjavax.persistence.EntityManager - JPA InterfaceInterface used to interact with the persistence context. em = emf.createEntityManagerEntityManagerFactory.createEntityManager() - JPA MethodCreate a new application-managed EntityManager
.();
try {
// TODO: Use the EntityManager to access the database
}
finally {
em.closeEntityManager.close() - JPA MethodClose an application-managed entity manager.();
}
The EntityManager
instance is obtained from the owning EntityManagerFactory
instance. Calling the close
EntityManager.close() - JPA MethodClose an application-managed entity manager. 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 be specified:
Map<String, String> properties = new HashMap<String, String>();
properties.put("javax.persistence.jdbc.user", "user1");
properties.put("javax.persistence.jdbc.password", "user1pwd");
EntityManagerjavax.persistence.EntityManager - JPA InterfaceInterface used to interact with the persistence context. em = emf.createEntityManagerEntityManagerFactory.createEntityManager(map) - JPA MethodCreate a new application-managed EntityManager
with the
specified Map of properties.(properties);
EntityTransaction
Operations that affect the content of the database (store, update, delete) must be performed within an active transaction. The EntityTransaction
javax.persistence.EntityTransaction - JPA InterfaceInterface used to control transactions on resource-local entity managers. interface represents and manages database transactions. Every EntityManager
javax.persistence.EntityManager - JPA InterfaceInterface used to interact with the persistence context. holds a single attached EntityTransaction
instance that is available via the getTransactionEntityManager.getTransaction() - JPA MethodReturn the resource-level
method: EntityTransaction
object.
try { em.getTransactionEntityManager.getTransaction() - JPA MethodReturn the resource-levelEntityTransaction
object.().beginEntityTransaction.begin() - JPA MethodStart a resource transaction.(); // Operations that modify the database should come here. em.getTransactionEntityManager.getTransaction() - JPA MethodReturn the resource-levelEntityTransaction
object.().commitEntityTransaction.commit() - JPA MethodCommit the current resource transaction, writing any unflushed changes to the database.(); } finally { if (em.getTransactionEntityManager.getTransaction() - JPA MethodReturn the resource-levelEntityTransaction
object.().isActiveEntityTransaction.isActive() - JPA MethodIndicate whether a resource transaction is in progress.()) em.getTransactionEntityManager.getTransaction() - JPA MethodReturn the resource-levelEntityTransaction
object.().rollbackEntityTransaction.rollback() - JPA MethodRoll back the current resource transaction.(); }
A transaction is started by a call to begin
EntityTransaction.begin() - JPA MethodStart a resource transaction. and ended by a call to either commit
EntityTransaction.commit() - JPA MethodCommit the current resource transaction, writing any unflushed changes to the database. or rollback
EntityTransaction.rollback() - JPA MethodRoll back the current resource transaction.. 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 RollbackException
javax.persistence.RollbackException - JPA ExceptionThrown by the persistence provider when {@link EntityTransaction#commit() EntityTransaction.commit()} fails. is thrown.