Persistence units

Persistence units are used to define different data sources and actions that will be applied to the data source when the application starts up.

Let's create a persistence unit in our persistence XML file:

<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0">

<persistence-unit name="local" transaction-type="RESOURCE_LOCAL">
<properties>
<property name ="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>

Here, we have just specified one persistence unit in our persistence XML file that we named local.

The persistence unit uses the javax.persistence.schema-generation.database.action property. When the application server starts up, it drops and creates the database schema for the databases, depending on the JPA mapping.

We can specify the data source. If we don't, the default data source will be used. 

To specify the data source, we use jta-data-source, as shown in the following code:

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">

<persistence-unit name="local" transaction-type="JTA">
<jta-data-source>jdbc/local_datasource</jta-data-source>
<properties>
<property name="javax.persistence.schema-
generation.database.action"
value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>

Here, we specified a data source that is itself configured on the application server. We could choose not to configure the URLs and credentials in the persistence XML file because we could do that in the application server and point to the data source specified. This is sufficient if we have one database in our application.

If we would like to specify several databases, we could have another persistence unit in the XML file:

    <persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">

<persistence-unit name="local" transaction-type="JTA">
<jta-data-source>jdbc/local_datasource</jta-data-source>
</persistence-unit>

<persistence-unit name="integration" transaction-type="JTA">
<jta-data-source>jdbc/int_datasource</jta-data-source>
</persistence-unit>

<persistence-unit name="production" transaction-type="JTA">
<jta-data-source>jdbc/prod_datasource</jta-data-source>
</persistence-unit>
</persistence>
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset