Propchange: websites/production/openjpa/content/builds/2.4.0/apache-openjpa/docs/ref_guide_dbsetup_dbsupport.html ------------------------------------------------------------------------------ svn:eol-style = native Added: websites/production/openjpa/content/builds/2.4.0/apache-openjpa/docs/ref_guide_dbsetup_isolation.html ============================================================================== --- websites/production/openjpa/content/builds/2.4.0/apache-openjpa/docs/ref_guide_dbsetup_isolation.html (added) +++ websites/production/openjpa/content/builds/2.4.0/apache-openjpa/docs/ref_guide_dbsetup_isolation.html Mon Jun 1 20:19:00 2015 @@ -0,0 +1,64 @@ ++ +
+OpenJPA typically retains the default transaction isolation level of the JDBC
+driver. However, you can specify a transaction isolation level to use through
+openjpa.jdbc.TransactionIsolation configuration property. The
+following is a list of standard isolation levels. Note that not all databases
+support all isolation levels.
default: Use the JDBC driver's default isolation level.
+OpenJPA uses this option if you do not explicitly specify any other.
none: No transaction isolation.
read-committed: Dirty reads are prevented; non-repeatable
+reads and phantom reads can occur.
read-uncommitted: Dirty reads, non-repeatable reads and
+phantom reads can occur.
repeatable-read: Dirty reads and non-repeatable reads are
+prevented; phantom reads can occur.
serializable: Dirty reads, non-repeatable reads, and phantom
+reads are prevented.
Example 4.8. + Specifying a Transaction Isolation +
+<property name="openjpa.jdbc.TransactionIsolation" value="repeatable-read"/> ++
+By default, OpenJPA uses standard forward-only JDBC result sets, and completely +instantiates the results of database queries on execution. When using a JDBC +driver that supports version 2.0 or higher of the JDBC specification, however, +you can configure OpenJPA to use scrolling result sets that may not bring all +results into memory at once. You can also configure the number of result objects +OpenJPA keeps references to, allowing you to traverse potentially enormous +amounts of data without exhausting JVM memory. ++
+You can also configure on-demand loading for individual collection and map +fields via large result set proxies. See +Section 6.4.2, “ + Large Result Set Proxies + ”. ++
+Use the following properties to configure OpenJPA's handling of result sets: ++
+: The number of objects to instantiate at once when traversing a result
+set. This number will be set as the fetch size on JDBC
+ objects used to obtain result sets. It also factors in to the
+number of objects OpenJPA will maintain a hard reference to when traversing a
+The fetch size defaults to -1, meaning all results will be instantiated +immediately on query execution. A value of 0 means to use the JDBC driver's +default batch size. Thus to enable large result set handling, you must set this +property to 0 or to a positive number. ++
+: The type of result set to use when executing database
+queries. This property accepts the following values, each of which corresponds
+exactly to the same-named
forward-only: This is the default.
+Different JDBC drivers treat the different result set types differently. Not all +drivers support all types. ++
+openjpa.jdbc.FetchDirection: The expected order in which you
+will access the query results. This property affects the type of data structure
+OpenJPA will use to hold the results, and is also given to the JDBC driver in
+case it can optimize for certain access patterns. This property accepts the
+following values, each of which corresponds exactly to the same-named
java.sql.ResultSet FETCH constant:
forward: This is the default.
+Not all drivers support all fetch directions. ++
+: The strategy OpenJPA will use to determine the size of result sets.
+This property is only used if you change the
+fetch batch size from its default of -1, so that OpenJPA begins to use on-demand
+result loading. Available values are:
query: This is the default. The first time you ask for the
+size of a query result, OpenJPA will perform a
+ query to determine the number of expected results. Note that
+depending on transaction status and settings, this can mean that the reported
+size is slightly different than the actual number of results available.
last: If you have chosen a scrollable result set type, this
+setting will use the
ResultSet.last method to move to
+the last element in the result set and get its index. Unfortunately, some JDBC
+drivers will bring all results into memory in order to access the last one. Note
+that if you do not choose a scrollable result set type, then this will behave
unknown. The default result set type is
forward-only, so you must change the result set type in
+order for this property to have an effect.
unknown: Under this setting OpenJPA will return
+Integer.MAX_VALUE as the size for any query result that uses on-demand
Example 4.16. + Specifying Result Set Defaults +
+<property name="openjpa.FetchBatchSize" value="20"/> +<property name="openjpa.jdbc.ResultSetType" value="scroll-insensitive"/> +<property name="openjpa.jdbc.FetchDirection" value="forward"/> +<property name="openjpa.jdbc.LRSSize" value="last"/> ++
Example 4.17. + Specifying Result Set Behavior at Runtime +
+import java.sql.*; +import org.apache.openjpa.persistence.jdbc.*; + +... + +Query q = em.createQuery("select m from Magazine m where m.title = 'JDJ'"); +OpenJPAQuery kq = OpenJPAPersistence.cast(q); +JDBCFetchPlan fetch = (JDBCFetchPlan) kq.getFetchPlan(); +fetch.setFetchBatchSize(20); +fetch.setResultSetType(ResultSetType.SCROLL_INSENSITIVE); +fetch.setFetchDirection(FetchDirection.FORWARD); +fetch.setLRSSizeAlgorithm(LRSSizeAlgorithm.LAST); +List results = q.getResultList(); ++
+Through the properties we've covered thus far, you can configure each
EntityManagerFactory to access a different
+database. If your application accesses multiple databases, we recommend that you
+maintain a separate persistence unit for each one. This will allow you to easily
+load the appropriate resource for each database at runtime, and to give the
+correct configuration file to OpenJPA's command-line tools during development.
+In its default configuration, OpenJPA obtains JDBC connections on an as-needed
EntityManagers do not retain a connection
+to the database unless they are in a datastore transaction or there are open
Query results that are using a live JDBC result set. At
+all other times, including during optimistic transactions,
+EntityManagers request a connection for each query, then
+immediately release the connection back to the pool.
+In some cases, it may be more efficient to retain connections for longer periods
+of time. You can configure OpenJPA's use of JDBC connections through the
+openjpa.ConnectionRetainMode configuration property. The
+property accepts the following values:
EntityManager obtains a
+single connection and uses it until the
+closes. Great care should be taken when using this property if the application
+cannot close the EntityManager (i.e. container-managed EntityManagers in a JEE
+Application Server). In this case the connection will remain open for an
+undefined time and the application may not be able to recover from a terminated
+connection (for example, if a TCP/IP timeout severs the connection to the database).
+For this reason the
always option should not be used with
transaction: A connection is obtained when each transaction
+begins (optimistic or datastore), and is released when the transaction
+completes. Non-transactional connections are obtained on-demand.
on-demand: Connections are obtained only when needed. This
+option is equivalent to the
transaction option when datastore
+transactions are used. For optimistic transactions, though, it means that a
+connection will be retained only for the duration of the datastore flush and
+You can also specify the connection retain mode of individual
+EntityManagers when you retrieve them from the
+Section 2.1, “
+ ” for details.
+openjpa.FlushBeforeQueries configuration property controls
+another aspect of connection usage: whether to flush transactional changes
+before executing object queries. This setting only applies to queries that would
+otherwise have to be executed in-memory because the
+property is set to false and the query may involve objects that have been
+changed in the current transaction. Legal values are:
true: Always flush rather than executing the query
+in-memory. If the current transaction is optimistic, OpenJPA will begin a
+non-locking datastore transaction. This is the default.
false: Never flush before a query.
with-connection: Flush only if the
+ has already established a dedicated connection to the datastore,
+otherwise execute the query in-memory.
+This option is useful if you use long-running optimistic transactions and want
+to ensure that these transactions do not consume database resources until
+commit. OpenJPA's behavior with this option is dependent on the transaction
+status and mode, as well as the configured connection retain mode described
+earlier in this section.
+The flush mode can also be varied at runtime using the OpenJPA fetch +configuration API, discussed in Chapter 9, + Runtime Extensions + . ++
+ +The table below describes the behavior of automatic flushing in various +situations. In all cases, flushing will only occur if OpenJPA detects that you +have made modifications in the current transaction that may affect the query's +results. ++
Table 4.2. + OpenJPA Automatic Flush Behavior +
|+||+FlushBeforeQueries = false +||+FlushBeforeQueries = true +||+FlushBeforeQueries = with-connection; +ConnectionRetainMode = on-demand +||+FlushBeforeQueries = with-connection; +ConnectionRetainMode = transaction or always +|
|+ +IgnoreChanges = true + +||+no flush +||+no flush +||+no flush +||+no flush +|
|+ +IgnoreChanges = false; no tx active + +||+no flush +||+no flush +||+no flush +||+no flush +|
|+ +IgnoreChanges = false; datastore tx active + +||+no flush +||+flush +||+flush +||+flush +|
|+ +IgnoreChanges = false; optimistic tx active + +||+no flush +||+flush +||
+no flush unless ||+flush +|
Example 4.11. + Specifying Connection Usage Defaults +
+<property name="openjpa.ConnectionRetainMode" value="on-demand"/> +<property name="openjpa.FlushBeforeQueries" value="true"/> ++
Example 4.12. + Specifying Connection Usage at Runtime +
+import org.apache.openjpa.persistence.*; + +// obtaining an em with a certain connection retain mode +Map props = new HashMap(); +props.put("openjpa.ConnectionRetainMode", "always"); +EntityManager em = emf.createEntityManager(props); ++
+Object queries often involve using SQL joins behind the scenes. You can
+configure OpenJPA to use either SQL 92-style join syntax, in which joins are
+placed in the SQL FROM clause, the traditional join syntax, in which join
+criteria are part of the WHERE clause, or a database-specific join syntax
+mandated by the
+DBDictionary. OpenJPA only supports outer joins when using
+SQL 92 syntax or a database-specific syntax with outer join support.
+openjpa.jdbc.DBDictionary plugin accepts the
+JoinSyntax property to set the system's default syntax. The available
traditional: Traditional SQL join syntax; outer joins are
database: The database's native join syntax. Databases that
+do not have a native syntax will default to one of the other options.
sql92: ANSI SQL92 join syntax. Outer joins are supported.
+Not all databases support this syntax.
+You can change the join syntax at runtime through the OpenJPA fetch +configuration API, which is described in Chapter 9, + Runtime Extensions + . ++
Example 4.9. + Specifying the Join Syntax Default +
+<property name="openjpa.jdbc.DBDictionary" value="JoinSyntax=sql92"/> ++
Example 4.10. + Specifying the Join Syntax at Runtime +
+import org.apache.openjpa.persistence.jdbc.*; + +... + +Query q = em.createQuery("select m from Magazine m where m.title = 'JDJ'"); +OpenJPAQuery kq = OpenJPAPersistence.cast(q); +JDBCFetchPlan fetch = (JDBCFetchPlan) kq.getFetchPlan(); +fetch.setJoinSyntax(JoinSyntax.SQL92); +List results = q.getResultList(); ++
+The JPA standard defines how to access JDBC connections from enterprise beans.
+OpenJPA also provides APIs to retrieve a connection directly from the
EntityManager's connection. If the
+EntityManager does not already have a connection, it will obtain
+one. The returned connection is only guaranteed to be transactionally consistent
EntityManager operations if the
+EntityManager is in a managed or non-optimistic transaction, if the
EntityManager has flushed in the current transaction, or
+if you have used the
+method to ensure that a datastore transaction is in progress. Always close the
+returned connection before attempting any other
+ operations. OpenJPA will ensure that the underlying native
+connection is not released if a datastore transaction is in progress.
Example 4.5. + Using the EntityManager's Connection +
+import java.sql.Connection; +import javax.persistence.EntityManager; +import javax.persistence.EntityManagerFactory; + +... + +EntityManager em = emf.createEntityManager(); +Connection conn = (Connection) em.unwrap(java.sql.Connection.class); + +// do JDBC stuff + +conn.close(); ++
+The example below shows how to use a connection directly from the
+DataSource, rather than using an
Example 4.6. + Using the EntityManagerFactory's DataSource +
+import java.sql.*; +import javax.sql.*; +import org.apache.openjpa.conf.*; +import org.apache.openjpa.persistence.*; + +... + +OpenJPAEntityManagerFactory kemf = OpenJPAPersistence.cast(emf); +OpenJPAConfiguration conf = kemf.getConfiguration(); +DataSource dataSource = (DataSource) conf.getConnectionFactory(); +Connection conn = dataSource.getConnection(); + +// do JDBC stuff + +conn.close(); ++
+In addition to connection pooling and prepared statement caching, OpenJPA +employs statement batching to speed up JDBC updates. Statement batching is +enabled by default for any JDBC driver that supports it. When batching is on, +OpenJPA automatically orders its SQL statements to maximize the size of each +batch. This can result in large performance gains for transactions that modify +a lot of data. ++
+You configure statement batching through the system DBDictionary, which is +controlled by the openjpa.jdbc.DBDictionary configuration property. You can +enable the statement batching by setting the batchLimit in the value. The batch +limit is the maximum number of statements OpenJPA will ever batch +together. A value has the following meaning: +
-1: Unlimited number of statements for a batch.
0: Disable batch support. This is the default for most
any positive number: Maximum number of statements for a batch.
+By default, the batch support is based on each Dictionary to define the default +batch limit. Currently only DB2 and Oracle dictionaries are set the default +batch limit to 100. The default batch limit for the rest of the dictionaries is set +to zero (disabled). ++
+The example below shows how to enable and disable statement batching via +your configuration properties. ++
Example 4.13. + Enable SQL statement batching +
+<property name="openjpa.jdbc.DBDictionary" value="db2(batchLimit=25)"/> +<property name="openjpa.jdbc.DBDictionary" value="oracle(batchLimit=-1)"/> +Or +<property name="openjpa.jdbc.DBDictionary" value="batchLimit=25"/> +<property name="openjpa.jdbc.DBDictionary" value="batchLimit=-1"/> ++
Example 4.14. + Disable SQL statement batching +
+<property name="openjpa.jdbc.DBDictionary" value="db2(batchLimit=0)"/> +Or +<property name="openjpa.jdbc.DBDictionary" value="batchLimit=0"/> ++
+By default, org.apache.openjpa.jdbc.kernel.BatchingConstraintUpdateManager +is the default statement batching implementation. OPENJPA also +provides another update manager +org.apache.openjpa.jdbc.kernel.BatchingOperationOrderUpdateManager for the +statements that required ordering. You can plug-in this update manager through +the "openjpa.jdbc.UpdateManager" property. Or you can plug-in your own +statement batching implementation by providing the implementation that extends +from AbstractUpdateManager, ConstraitUpdateManager or OperationOrderUpdateManager. +Add this implementation +class as a property in the persistence.xml file. For example, a custom +statement batching implementation mycomp.MyUpdateManager extends +ConstraitUpdateManager. You specify this implementation in the persistence.xml +file as the following example: ++
Example 4.15. + Plug-in custom statement batching implementation +
+<property name="openjpa.jdbc.UpdateManager" value="mycomp.MyUpdateManager"/> ++
+You can use OpenJPA with any third-party
+. There are multiple ways of telling OpenJPA about a
DataSource into the map passed to
+Persistence.createEntityManagerFactory under the
DataSource into JNDI, and then specify its
+location in the
non-jta-data-source element of the
+JPA XML format (depending on
DataSource is managed by JTA), or in the
+Specify the full class name of the
+implementation in the
openjpa.ConnectionDriverName property in place of a JDBC
+driver. In this configuration OpenJPA will instantiate an instance of the named
+class via reflection. It will then configure the
+ with the properties in the
+The features of OpenJPA's own
+also be used with third-party implementations. OpenJPA layers on top of the
DataSource to provide the extra
+functionality. To configure these features use the
openjpa.ConnectionFactoryProperties property described
+in the previous section.
Example 4.2. + Properties File for a Third-Party DataSource +
+<property name="openjpa.ConnectionDriverName" value="oracle.jdbc.pool.OracleDataSource"/> +<property name="openjpa.ConnectionProperties" + value="PortNumber=1521, ServerName=saturn, DatabaseName=solarsid, DriverType=thin"/> +<property name="openjpa.ConnectionFactoryProperties" value="QueryTimeout=5000"/> ++
+You can also force the Apache Commons DBCP BasicDataSource to be used for
+connection pooling when provided on the classpath by substituting it as the
ConnectionDriverName and setting
ConnectionProperties=DriverClassName to the actual JDBC
+driver value -
+<property name="openjpa.ConnectionDriverName" value="org.apache.commons.dbcp.BasicDataSource"/> +<property name="openjpa.ConnectionProperties" + value="DriverClassName=oracle.jdbc.pool.OracleDataSource, PortNumber=1521, ServerName=saturn, DatabaseName=solarsid, DriverType=thin, MaxIdle=0"/> +<property name="openjpa.ConnectionFactoryProperties" value="QueryTimeout=5000"/> ++
+Certain application servers automatically enlist their
+s in global transactions. When this is the case, OpenJPA should not
+attempt to commit the underlying connection, leaving JDBC transaction completion
+to the application server. To notify OpenJPA that your third-party
+DataSource is managed by the application server, use the
jta-data-source element of your
+persistence.xml file or set the
openjpa.ConnectionFactoryMode property to
+Note that OpenJPA can only use managed
+it is also integrating with the application server's managed transactions. Also
+note that all XA
DataSources are enlisted, and you must
+set this property when using any XA
+When using a managed
DataSource, you should also
+configure a second unmanaged
DataSource that OpenJPA can
+use to perform tasks that are independent of the global transaction. The most
+common of these tasks is updating the sequence table OpenJPA uses to generate
+unique primary key values for your datastore identity objects. Configure the
DataSource using the
persistence.xml element, or OpenJPA's various
+"2" connection properties, such as
+properties are outlined in Chapter 2,
Example 4.3. + Managed DataSource Configuration +
+<!-- managed DataSource --> +<jta-data-source>java:/OracleXASource</jta-data-source> +<properties> + <!-- use OpenJPA's built-in DataSource for unmanaged connections --> + <property name="openjpa.Connection2UserName" value="scott"/> + <property name="openjpa.Connection2Password" value="tiger"/> + <property name="openjpa.Connection2URL" value="jdbc:oracle:thin:@CROM:1521:OpenJPADB"/> + <property name="openjpa.Connection2DriverName" value="oracle.jdbc.driver.OracleDriver"/> +</properties> ++
+As mentioned above, the JTA and Non-JTA DataSources may be passed in as configuration properties
+at EntityManagerFactory creation. Either the JPA standard properties (
+or their OpenJPA specific equivalents (
openjpa.ConnectionFactory2Name) may be used. One use case for this function is to
+store production connection information in configuration files but override the value when testing.
Example 4.4. + Setting DataSource at Runtime +
Map<Object,Object> props = new HashMap<Object,Object>(); +props.put("javax.persistence.jtaDataSource", "jdbc/myDataSource"); +props.put("javax.persistence.nonJtaDataSource", "jdbc/myNonJTADataSource"); +emf = Persistence.createEntityManagerFactory("example", props);+
+The JPA specification allows the DataSource (ConnectionFactory) to be specified on the +EntityManagerFactory. OpenJPA extends this support and allows each EntityManager to override the +DataSource from the EntityManagerFactory. It's expected that the EntityManagerFactory will also be +configured with a valid JTA / Non-JTA DataSource. The DataSource configured on the +EntityManagerFactory will be used to obtain a DBDictionary and (rarely) to gather some information +about the database in use (e.g. version, JDBC driver version). ++
+ If the EntityManagerFactory is not configured with a valid DataSource there are + a few additional caveats. +
openjpa.DBDictionary property must be
+ used to ensure the correct DBDictionary is used.
OpenJPA will always attempt to obtain a DataSource from JNDI + based on the configuration for the EntityManagerFactory. When a JNDI name is + specified on the EntityManager this lookup happens slightly earlier than + normal. If the lookup fails the JNDI name provided at EntityManager creation + will be set into the EntityManagerFactory's configuration and used in + subsequent attempts.
+ In effect this option allows a single set of entity definitions to be shared + between multiple database instances or schemas within an instance. This can be + highly beneficial when there are a large number of entity definitions (e.g. > + 200), or a large number of databases / schemas in use. ++
The same database type and version must be used by each + EntityManager. OpenJPA will use the same DBDictionary for each + EntityManager and will make no attempt to alter SQL syntax + between EntityManager instances. ++
It is the application's responsibility to ensure + that the schema is identical on each database.
The application may not specify schema names for + individual entities.
The DataSource (ConnectionFactory) name may only be + specified when the EntityManager is created. The DataSource + may not be switched while an EntityManager is in use. ++
The L2 cache (DataCache) should not be used if + different DataSources are specified for each EntityManager+
SynchronizeMappings should not be used with this + feature.
Table and Sequence generators should not be used + with this feature.
It is not required, but is recommended that the
openjpa.DBDictionary property be specified when
+ using this feature
+ If a JTA DataSource is not available when the EntityManager is created, an
IllegalArgumentException will be thrown.
+ The EntityManager will not fall back to the JTA DataSource defined in the
+ The same logic applies if a Non-JTA DataSource is not available when the + EntityManager is created. OpenJPA will not fall back to the configured + Non-JTA DataSource. ++
Table of Contents
+OpenJPA deployment includes choosing a factory deployment strategy, and in a +managed environment, optionally integrating with your application server's +managed and XA transactions. This chapter examines each aspect of deployment in +turn. ++
+OpenJPA offers two
+The JPA Overview describes the
+ class. You can use
Persistence to obtain
EntityManagerFactory instances, as demonstrated in
+ . OpenJPA also extends
Persistence to add additional
+EntityManagerFactory creation methods. The
+Javadoc details these extensions.
+After obtaining the factory, you can cache it for all
+EntityManager creation duties. OpenJPA factories support being
+bound to JNDI as well.
+Java EE application servers allow you to inject
+entity managers into your session beans using the
+ annotation. See your application server documentation for details.
+ OpenJPA provides an interface for a provider to implement
+ connection password encryption. Whenever a connection password
+ is needed, the
decrypt(String) method will be invoked. See
+ for the detailed Javadoc.
+ Notes: +
+ It is an OpenJPA user responsibility to implement the
+ interface. There is no default implementation.
+ The interface has an
+ but it is not called by the OpenJPA runtime.
+It is possible to adapt OpenJPA to access a non-relational datastore by creating
+an implementation of the
+org.apache.openjpa.kernel.StoreManager interface. OpenJPA
+provides an abstract
StoreManager implementation to
+facilitate this process. See the
+Javadoc for details.