openjpa-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From conflue...@apache.org
Subject [CONF] OpenJPA > Begin using OpenJPA - The Basics
Date Wed, 03 Mar 2010 20:15:00 GMT
<html>
<head>
    <base href="http://cwiki.apache.org/confluence">
            <link rel="stylesheet" href="/confluence/s/1519/1/1/_/styles/combined.css?spaceKey=openjpa&amp;forWysiwyg=true"
type="text/css">
    </head>
<body style="background-color: white" bgcolor="white">
<div id="pageContent">
<div id="notificationFormat">
<div class="wiki-content">
<div class="email">
     <h2><a href="http://cwiki.apache.org/confluence/display/openjpa/Begin+using+OpenJPA+-+The+Basics">Begin
using OpenJPA - The Basics</a></h2>
     <h4>Page <b>edited</b> by             <a href="http://cwiki.apache.org/confluence/display/~scottq@us.ibm.com">Scott
Matthew Quint</a>
    </h4>
     
          <br/>
     <div class="notificationGreySide">
         <h1><a name="BeginusingOpenJPA-TheBasics-Introduction"></a>Introduction</h1>

<p>OpenJPA is an open source implementation of the Java JPA (Java Persistence API) specification
from Apache. JPA provides an agnostic Java-based API for storing and retrieving information
to a backend database. It has a canonical query language named Java Persistence Query Language,
or JPQL, that blends with the programming methods of Java and eliminates the need to tailor
database queries for a particular database. However, JPA also supports native SQL which can
be used for quick ports with a known backend database. This tutorial is designed to walk you
through the steps of setting up a simple <font color="black">web application</font>
to use OpenJPA Geronimo and to transact the derby database that comes with Geronimo. The tutorial
code uses a simple Java Server Page (JSP), backed up by some basic classes. It displays a
table of inventory items and categories. In this tutorial, we will not dive into details regarding
the JSP code. Its purpose is to be a window through which you can examine OpenJPA. &nbsp;The
intended audience for this tutorial is those with some knowledge and understanding of the
Java programming language and who are just beginning with OpenJPA. To start, you must download
the following requirements and install them on your computer. For the purposes of this tutorial,
we are using Eclipse as the IDE and Microsoft Windows as the operating system of choice.&nbsp;</p>

<h2><a name="BeginusingOpenJPA-TheBasics-Prerequisites"></a>Prerequisites</h2>

<p><b>Geronimo V2.2:</b> You can get it <a href="http://www.apache.org/dyn/closer.cgi/geronimo/2.2/geronimo-tomcat6-javaee5-2.2-bin.zip"
rel="nofollow">here</a>. Download this file and unzip it to a permanent location.
There is no installer. The server will run from the command line.</p>

<p><b>Java (J2SE) V1.6:</b> This tutorial was developed and tested with
Java V1.6. If you don't already have Java V1.6 you can get the IBM JDK <a href="http://www.ibm.com/developerworks/java/jdk/"
rel="nofollow">here</a> or the Sun JDK <a href="https://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_Developer-Site/en_US/-/USD/ViewProductDetail-Start?ProductRef=jdk-6u16-oth-JPR@CDS-CDS_Developer"
rel="nofollow">here</a>.</p>

<p><b>Eclipse V3.2 or later:</b> This version has annotation support included.
Annotations play a large role in OpenJPA.&nbsp; <a href="http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/galileo/SR1/eclipse-jee-galileo-SR1-win32.zip"
rel="nofollow">Download</a>Eclipse 3.2 or later.</p>

<p><b>Apache OpenJPA library:</b> For the purpose of implementing this tutorial
you can select<br/>
OpenJPA v1.2 or greater. You can download <a href="http://openjpa.apache.org/downloads.html"
rel="nofollow">Apache OpenJPA</a> from the Apache site. Note that the Milestone (openjpa-all-2.0.0-M3.jar
as of this writing) is an early release of OpenJPA 2.0 and may have some instabilities. No
issues have been noted for the usage in this tutorial.</p>

<p><b>The tutorial code files</b>: <a href="/confluence/download/attachments/12320826/OpenJPAWebAppTutorial.zip?version=5"
title="attached source files">These files</a> are provided with this tutorial. You
will add them to your Eclipse project.</p>

<h1><a name="BeginusingOpenJPA-TheBasics-SetupandRunningtheSample"></a>Setup
and Running the Sample</h1>

<p>Now, that you have all the prerequisites for this tutorial downloaded and installed,
the following sections will walk you through the Eclipse project setup and the OpenJPA configuration.
Make sure you read through and follow each part carefully. &nbsp;</p>

<h2><a name="BeginusingOpenJPA-TheBasics-SettingupEclipse"></a>Setting up
Eclipse</h2>

<p>After installing Eclipse, create a new project in a dedicated workspace for the tutorial.
Complete the following setup instructions: First, make sure your Eclipse environment is updated
and has the Geronimo plugin. If you do not know how to do that, follow the instructions found
at the <a href="http://geronimo.apache.org/geronimo-eclipse-plugin-installation-instructions.html"
rel="nofollow">Geronimo website</a>.</p>

<ol>
	<li>Create a new Java project in Eclipse called, <b>"OpenJPATutorial"</b>.
	<ul>
		<li>From the menu, select: <b>File-&gt;New-&gt;Enterprise Application
Project</b>. (If <b>Enterprise Application Project</b> is not available
as an option, select <b>Project</b> and then choose <b>Enterprise      
Application Project</b> from the list. Then click on the <b>Next</b> button).<br/>
When the New Project settings dialog appears, use the following settings:
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image001.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" /></li>
	</ul>
	</li>
	<li>Under the <b>Target Runtime</b> section, select <b>Apache Geronimo
v2.2</b>.
	<ul>
		<li>If you do not already have Geronimo setup in Eclipse then you will have to do
so now. Click on the <b>New...</b> button.</li>
		<li>If Apache Geronimo v2.2 does not appear in the list under <b>Apache</b>,
click the <b>Download additional server adapters</b> link at the top right of
the dialog. If the adapter does not appear in that list then follow the <a href="http://geronimo.apache.org/geronimo-eclipse-plugin-installation-instructions.html"
rel="nofollow">directions from the Geronimo site</a>.
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image002.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" /></li>
		<li>Select <b>Apache-&gt;Apache Geronimo v2.2</b></li>
		<li>Click <b>Next</b>.
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image003.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" /></li>
		<li>Set the JRE to <b>jre6</b> if it is not already set.</li>
		<li>Browse for the install directory of Geronimo v2.2 on your system.</li>
		<li>Click <b>Finish</b>. You should see the following:
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image001.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" /></li>
	</ul>
	</li>
	<li>Now, click the <b>Next</b> button. You should see this:
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image004.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" />
	<ul>
		<li>Check the <b>Generate application.xml deployment descriptor</b> option.</li>
		<li>Click the <b>New Module...</b> button:
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image005.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" /></li>
		<li>De-select <b>Create default modules</b>.</li>
		<li>Select       the <b>Web</b> option.</li>
		<li>Click <b>Next</b>.
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image006.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" /></li>
		<li>Click <b>Finish</b>. You will see the following:
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image007.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" /></li>
		<li>Click <b>Finish</b>.
<br clear="all" />
<br clear="all" /></li>
	</ul>
	</li>
	<li>Now, your Project Explorer should look like this (partially expanded):
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image008.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" />
	<ul>
		<li>If you double-click on the <b>Deployment Descriptor: OpenJPATutorial</b>,
you should see the application.xml open:
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image009.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" /></li>
	</ul>
	</li>
	<li>Now we will bring in the sample code. The easiest way to add the sample code is
     to find the source provided with this tutorial and copy it to the src      folder under
the <b>OpenJPATutorialWeb</b> folder in your project directory in Windows Explorer:
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image010.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" />
	<ul>
		<li>Now go back to Eclipse. Right-click on the <b>OpenJPATutorialWeb</b>
folder in the Project Explorer view and select <b>Refresh,</b> or press the <b>F5</b>
key on your keyboard. Now you will see this:
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image011.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" />
Notice that all the source files compile without error. That is because Geronimo comes with
OpenJPA v1.1 built in.
<br clear="all" />
<br clear="all" /></li>
	</ul>
	</li>
	<li><font color="black">Now copy the index.jsp file from the tutorial into the
Web Content directory under the Project directory in Windows Explorer:</font><br
clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image012.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" />
	<ul>
		<li><font color="black">Got to the Project Explorer and refresh the project.
You should see this:</font><br clear="all" />
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image013.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" /></li>
	</ul>
	</li>
</ol>


<h2><a name="BeginusingOpenJPA-TheBasics-RunningandConfiguringGeronimoandDerby"></a>Running
and Configuring Geronimo and Derby</h2>

<p>Geronimo has no installer and runs from the command line. Here are some quick instructions
to get you started.</p>
<ol>
	<li>In Windows, open a command prompt and navigate to the Geronimo <b>bin</b>
directory.</li>
	<li>Type the command:
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">start-server
</pre>
</div></div>
<p><br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image014.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" />
Press the <b>Enter</b> key.
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image015.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" /></p></li>
	<li>Open a web browser and go to the address:
<br clear="all" />
<br clear="all" />
<a href="http://localhost:8080/console" rel="nofollow">http://localhost:8080/console</a><br
clear="all" />
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image016.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" />
<br clear="all" />
The default password is <em>manager</em>.
<br clear="all" />
<br clear="all" /></li>
	<li>You will come to the Welcome page. On the left menu, at the bottom, find the  
   section for the Embedded DB. This is the Derby database control page.
<br clear="all" />
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image017.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" /></li>
	<li><font color="black">Click on the link for the</font> <font color="black"><b>DB
Manager</b></font><font color="black">.</font></li>
	<li>You will see two sections: <b>DB Viewer</b> and <b>Run SQL</b>.</li>
	<li>In the Run SQL section, in the text field labeled Create DB, type in <b>StoreSystem</b>.
This is the name of the database that the OpenJPA sample is configured to transact.
<br clear="all" />
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image018.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" /></li>
	<li><font color="black">Click on the</font> <font color="black"><b>Create</b></font>
<font color="black">button. You should now see the</font> <font color="black"><b>StoreSystem</b></font>
<font color="black">database appear in the</font><font color="black"><b>DB
Viewer</b></font> <font color="black">section</font>.
<br clear="all" />
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image019.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" /></li>
	<li><font color="black">We are now ready to deploy and run the sample code.</font></li>
</ol>


<p><br clear="all" /></p>

<h2><a name="BeginusingOpenJPA-TheBasics-RunningandDeployingtheSampleCodeinGeronimo"></a>Running
and Deploying the Sample Code in Geronimo</h2>

<p>The sample code provided with this tutorial is working code. It is a simple inventory
database program that shows items and categories. But even this simple example requires the
ability to add, edit and delete entries. It requires the ability to sort and filter database
queries and it requires the identification of the relationship of the items to the categories.
In this example, the relationship is <b>one to many</b>. Knowing that relationship
is important to how the code is written. Before we analyze the code and OpenJPA, we will first
deploy the sample and see it work. To deploy the sample code follow these instructions:</p>
<ol>
	<li>In Eclipse, in the Project Explorer, right click on the OpenJPATutorial project
and select: <b>Export-&gt;EAR file</b>.
<br clear="all" />
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image020.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" /></li>
	<li>In the      Ear Export dialog, find a convenient place to put the exported EAR
file.</li>
	<li>Check      the <b>Overwrite existing file</b> check box.
<br clear="all" />
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image021.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" /></li>
	<li>Click <b>Finish</b>.</li>
	<li>Go out to Windows Explorer and copy the file <b>TutorialDeploymentPlan.xml</b>
to the location of the exported ear. This is the deployment plan that Geronimo requires to
deploy the application.
<br clear="all" />
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image022.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" /></li>
	<li>Open the Geronimo console in a web browser and log in.</li>
	<li>In the Console Navigation menu on the left, under the <b>Applications</b>
section, click on the <b>Deploy New</b> item.</li>
	<li>Browse to the location of the exported EAR file and the deployment plan XML file.
<br clear="all" />
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image023.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" /></li>
	<li>Click on the <b>Install</b> button. You should see this.
<br clear="all" />
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image024.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" /></li>
	<li>In the Console Navigation menu on the left, under the <b>Applications</b>
section, click on the <b>Web App WARs</b> item.
	<ul>
		<li>Notice that the OpenJPATutorial application is now listed and that there is a
clickable link under the URL heading:
<br clear="all" />
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image025.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" /></li>
	</ul>
	</li>
	<li>Click on the link <b>OpenJPATutorial</b> and now you should see this:
<br clear="all" />
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image026.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" />
Each of the buttons will execute OpenJPA code. The lists are filled by running queries on
the Derby database.
	<ol>
		<li>Add a some categories and items</li>
		<li>Make sure you test each of the buttons and see the results.
<br clear="all" /></li>
	</ol>
	</li>
</ol>


<h1><a name="BeginusingOpenJPA-TheBasics-ExaminingtheSampleCode"></a>Examining
the Sample Code</h1>

<p>Now that everything is set up and you have seen it work, let's look more closely
at the parts of the code that use OpenJPA. The JSP code is just a prop to explore OpenJPA
and we will not examine it.The sample application source code is provided for this tutorial
and you may run as-is with no customizations. However, you have the option of reproducing
the code manually using the following explanations. Whichever method you choose, locate the
code that corresponds to explanations as you follow along.</p>
<ul>
	<li>Java code: This tutorial comes with the following java source files:
	<ul>
		<li>index.jsp: This is the interface code only. It does call into other classes but
it does not use any OpenJPA code directly.</li>
		<li>InventoryEntityBroker.java:&nbsp;This class contains methods that encapsulate
the OpenJPA handling code. It is provided as a way to separate OpenJPA functionality from
the web interface.</li>
		<li>InventoryItem.java: This is an OpenJPA Entity class file. This file is an example
of a simple OpenJPA Entity with a relationship.</li>
		<li>InventoryCategory.java: This is an OpenJPA Entity class file. This file is an
example of a simple OpenJPA Entity with a relationship.</li>
	</ul>
	</li>
	<li>Persistence code: Each entity concept that would be a database table will be its
own class. In this case, the tables are called "InventoryItem" and "InventoryCategory". Annotations
in the Java file will associate the properties with the database columns. The annotation,
<font color="#646464">@Column</font>, maps the property name to the column name
for synchronization with the database. If the table corresponding tables do not exist, OpenJPA
can use these annotations to create the tables' schema dynamically based on the property type
and length.</li>
</ul>


<div class="code panel" style="border-style: solid;border-width: 1px;"><div class="codeHeader
panelHeader" style="border-bottom-width: 1px;border-bottom-style: solid;"><b>InventoryCategory.java</b></div><div
class="codeContent panelContent">
<pre class="code-java"><span class="code-keyword">package</span> tutorial;
<span class="code-keyword">import</span> java.util.List;

<span class="code-keyword">import</span> javax.persistence.CascadeType;
<span class="code-keyword">import</span> javax.persistence.Column;
<span class="code-keyword">import</span> javax.persistence.Entity;
<span class="code-keyword">import</span> javax.persistence.GeneratedValue;
<span class="code-keyword">import</span> javax.persistence.GenerationType;
<span class="code-keyword">import</span> javax.persistence.Id;
<span class="code-keyword">import</span> javax.persistence.OneToMany;
<span class="code-keyword">import</span> javax.persistence.Version;

@Entity
<span class="code-keyword">public</span> class InventoryCategory
{
   <span class="code-keyword">private</span> <span class="code-object">int</span>
version;
   <span class="code-keyword">private</span> <span class="code-object">int</span>
id;

   <span class="code-keyword">private</span> <span class="code-object">String</span>
categoryName;
   <span class="code-keyword">private</span> <span class="code-object">String</span>
categoryDescription;

   List&lt;InventoryItem&gt; items;

   <span class="code-keyword">public</span> InventoryCategory(){}

   @Column(name = <span class="code-quote">"categoryName"</span>)
   <span class="code-keyword">public</span> <span class="code-object">String</span>
getCategoryName()
   {
      <span class="code-keyword">return</span> categoryName;
   }

   <span class="code-keyword">public</span> void setCategoryName(<span class="code-object">String</span>
name)
   {
      <span class="code-keyword">this</span>.categoryName = name;
   }

   @Column(name = <span class="code-quote">"itemDescription"</span>)
   <span class="code-keyword">public</span> <span class="code-object">String</span>
getCategoryDescription()
   {
      <span class="code-keyword">return</span> categoryDescription;
   }

   <span class="code-keyword">public</span> void setCategoryDescription(<span
class="code-object">String</span> description)
   {
      <span class="code-keyword">this</span>.categoryDescription = description;
   }

   @Version
   @Column(name = <span class="code-quote">"version_field"</span>)
   <span class="code-comment">// not required
</span>   <span class="code-keyword">public</span> <span class="code-object">int</span>
getVersion()
   {
       <span class="code-keyword">return</span> version;
   }

   <span class="code-keyword">public</span> void setVersion(<span class="code-object">int</span>
version)
   {
      <span class="code-keyword">this</span>.version = version;
   }

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   <span class="code-keyword">public</span> <span class="code-object">int</span>
getId()
   {
      <span class="code-keyword">return</span> id;
   }

   <span class="code-keyword">public</span> void setId(<span class="code-object">int</span>
id)
   {
      <span class="code-keyword">this</span>.id = id;
   }

   @OneToMany(targetEntity=tutorial.InventoryItem.class,
      cascade=CascadeType.ALL,
      mappedBy=<span class="code-quote">"category"</span>)
   <span class="code-keyword">public</span> List&lt;InventoryItem&gt;
getItems()
   {
      <span class="code-keyword">return</span> items;
   }

   <span class="code-keyword">public</span> void setItems(List&lt;InventoryItem&gt;
items)
   {
      <span class="code-keyword">this</span>.items = items;
   }

   <span class="code-keyword">public</span> void addItem(InventoryItem item)
   {
      <span class="code-keyword">this</span>.items.add(item);
   }
}
</pre>
</div></div>
<p><br clear="all" /></p>
<div class='panelMacro'><table class='infoMacro'><colgroup><col width='24'><col></colgroup><tr><td
valign='top'><img src="/confluence/images/icons/emoticons/information.gif" width="16"
height="16" align="absmiddle" alt="" border="0"></td><td><b>Note</b><br
/><p>In this example, the property annotations ( <font color="#646464">@Column</font>,<font
color="#646464">@Version</font>, and <font color="#646464">@Id</font>)
are placed on the getter methods. They can alternatively be placed on the property declarations.
For more information on these annotations and to see what other annotations are in OpenJPA,
see the <a href="http://openjpa.apache.org/builds/latest/docs/manual/jpa_overview_meta.html"
rel="nofollow">Apache OpenJPA 2.0 User's Guide: Chapter 5</a></p>
<ul>
	<li>The annotated class and property declarations are all that are required.</li>
	<li>The <font color="#646464"><b>@Id</b></font> annotation
is needed as the unique identifier (primary key) for each record.</li>
	<li>The <font color="#646464"><b>@Version</b></font> annotation
is common practice. It ensures data integrity during merges and acts as an optimistic concurrency
control.</li>
	<li>Every property must have both a getter and a setter and the standard case convention
must be observed.<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;°&nbsp;
Correct: <font color="#7f0055"><b>public</b></font> <font color="#7f0055"><b>void</b></font>
<font color="black">setCategoryName(String name)</font><br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;°&nbsp;
Incorrect: <font color="#7f0055"><b>public</b></font> <font color="#7f0055"><b>void</b></font>
<font color="black">setcategoryname(String name)</font></li>
</ul>
</td></tr></table></div>
<p><br clear="all" /></p>
<ul>
	<li>Persistence.xml: JPA requires the use of a XML file called the "persistence.xml"
that describes how to access the data. The XML file must be created in the META-INF directory.
The META-INF directory containing the persistence.xml must be located with the source files.
<br clear="all" />
<br clear="all" />
<br clear="all" />  <img src="/confluence/download/attachments/12320826/image027.jpg"
align="absmiddle" border="0" /><br clear="all" />
<br clear="all" />
In the following example, the file only requires a few fields.
<br clear="all" />
<br clear="all" />
<div class="code panel" style="border-style: solid;border-width: 1px;"><div class="codeHeader
panelHeader" style="border-bottom-width: 1px;border-bottom-style: solid;"><b>META-INF/persistence.xml</b></div><div
class="codeContent panelContent">
<pre class="code-xml">&lt;persistence xmlns=http://java.sun.com/xml/ns/persistence
    <span class="code-keyword">xmlns:xsi</span>=http://www.w3.org/2001/XMLSchema-instance
    version=<span class="code-quote">"1.0"</span>&gt;
    <span class="code-tag">&lt;persistence-unit name=<span class="code-quote">"InventorySystem"</span>
transaction-type=<span class="code-quote">"RESOURCE_LOCAL"</span>&gt;</span>
        <span class="code-tag">&lt;class&gt;</span>tutorial.InventoryItem<span
class="code-tag">&lt;/class&gt;</span>
        <span class="code-tag">&lt;class&gt;</span>tutorial.InventoryCategory<span
class="code-tag">&lt;/class&gt;</span>
        <span class="code-tag">&lt;properties&gt;</span>
            <span class="code-tag">&lt;property name=<span class="code-quote">"openjpa.jdbc.SynchronizeMappings"</span>
value=<span class="code-quote">"buildSchema"</span>/&gt;</span>
            <span class="code-tag">&lt;property name=<span class="code-quote">"openjpa.ConnectionURL"</span>
value=<span class="code-quote">"jdbc:derby://localhost:1527/StoreSystem"</span>/&gt;</span>
            <span class="code-tag">&lt;property name=<span class="code-quote">"openjpa.ConnectionDriverName"</span>
value=<span class="code-quote">"org.apache.derby.jdbc.ClientDriver"</span>/&gt;</span>
        <span class="code-tag">&lt;/properties&gt;</span>
    <span class="code-tag">&lt;/persistence-unit&gt;</span>
<span class="code-tag">&lt;/persistence&gt;</span>
</pre>
</div></div>
<p><br clear="all" />
<br clear="all" /></p></li>
	<li>The following elements are specific to this tutorial:
	<ul>
		<li><b>persistence-unit</b>: the <b>name</b> is the table
name to bind. In this case it is        'person'.</li>
		<li><b>class</b>: the java class that is bound to the table 'person'.</li>
		<li><b>property:</b> openjpa.jdbc.SynchronizeMappings: This tells OpenJPA
to automatically create the table with the class definition if a table does not already exist.</li>
		<li><b>property:</b> openjpa.ConnectionURL: The URL of the database connection.</li>
		<li><b>property:</b> openjpa.ConnectionDriverName: the class name of the
JDBC driver for Derby. This must be available via the classpath. In this tutorial, the driver
is built into Geronimo so no extra actions are needed.</li>
	</ul>
	</li>
	<li>A complete explanation of the persistence.xml is in the <a href="http://openjpa.apache.org/builds/latest/docs/manual/jpa_overview_persistence.html"
rel="nofollow">Apache OpenJPAV2.0 user's Guide: Chapter 6</a><br clear="all" />
<br clear="all" /></li>
	<li>Create the Entity Manager. In the provided code, the EntityManager is a property
of the InventoryEntityBroker class. The Entity Manager controls the interaction with the database.
You must use the Entity Manager to start or access transactions or to send queries.
	<ul>
		<li>The following code must be added before using any of the persistence APIs (If
you are using the provided sample code, this is already included):
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">EntityManagerFactory factory = 	Persistence.createEntityManagerFactory(<span
class="code-quote">"InventorySystem"</span>,
      <span class="code-object">System</span>.getProperties());

EntityManager em = factory.createEntityManager();
</pre>
</div></div></li>
		<li>Note that the name, <font color="#2a00ff">"InventorySystem"</font>,
is the same one identified in the persistence.xml.</li>
		<li>This code can be placed just before a query or transaction or they can be class
properties.</li>
		<li>Regardless of the scope, the EntityManager and the EntityManagerFactory should
be closed when they are no longer needed:
<br clear="all" />
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">...
em.close();
factory.close();
...
</pre>
</div></div></li>
		<li>The EntityManagerFactory and EntityManager full descriptions are in the following
OpenJPA documentation:
		<ul>
			<li>EntityManagerFactory: <a href="http://openjpa.apache.org/builds/latest/docs/manual/jpa_overview_emfactory.html"
rel="nofollow">http://openjpa.apache.org/builds/latest/docs/manual/jpa_overview_emfactory.html</a></li>
			<li>EntityManager: <a href="http://openjpa.apache.org/builds/latest/docs/manual/jpa_overview_em.html"
rel="nofollow">http://openjpa.apache.org/builds/latest/docs/manual/jpa_overview_em.html</a></li>
		</ul>
		</li>
	</ul>
	</li>
</ul>


<ul>
	<li>DB interface class. In this example, the InventoryEntityBroker class contains all
the OpenJPA database interaction code. This is not required but it is a good idea for keeping
the functionality componentized. For example, if you want to pull all of the records from
the InventoryItem table, the code would look like this:
<br clear="all" />
<div class="code panel" style="border-width: 1px;"><div class="codeHeader panelHeader"
style="border-bottom-width: 1px;"><b>InventoryEntityBroker.java</b></div><div
class="codeContent panelContent">
<pre class="code-java">...
List&lt;Person&gt; getAllItems()
{
     Query q = em.createQuery(<span class="code-quote">"SELECT item FROM InventoryItem
item"</span>);

     <span class="code-keyword">return</span> (List&lt;InventoryItem&gt;)q.getResultList();
}
...
</pre>
</div></div>
<div class="code panel" style="border-width: 1px;"><div class="codeHeader panelHeader"
style="border-bottom-width: 1px;"><b>index.jsp</b></div><div class="codeContent
panelContent">
<pre class="code-java">...
List&lt;InventoryItem&gt; itemList = getAllItems();
...
</pre>
</div></div>
	<ul>
		<li>All of the specific APIs are described in the OpenJPA <a href="http:/openjpa.apache.org/builds/latest/docs/javadoc/index.html"
rel="nofollow">javadoc</a></li>
		<li>Notice that the Query is not standard SQL. It is actually JPQL, which is a specialized
form of query language specifically designed for JPA.
		<ul class="alternate" type="square">
			<li>In the JPQL statement, "<font color="#2a00ff">SELECT item FROM InventoryItem
item</font>", notice that InventoryItem has the same case as the class InventoryItem.</li>
			<li>JPQL uses java objects in the query and not the database table names. The statement
identifies the variable for InventoryItem as "<font color="#2a00ff">item</font>".</li>
			<li>JPQL provides an object oriented query language that is independent of the database
being queried.&nbsp; So, regardless of which database being used, the JPQL does not change.&nbsp;
The JPA runtime takes care of doing the translation from the object world to the desired relational
database.</li>
			<li>For more information on JPQL, check out this <a href="http://java.sun.com/javaee/5/docs/tutorial/backup/update3/doc/QueryLanguage.html"
rel="nofollow">Java Persistence Querly Language reference.</a><br clear="all"
/>
<br clear="all" /></li>
		</ul>
		</li>
	</ul>
	</li>
	<li>Also in the InventoryEntityBroker is code to add entries the database tables. Since
you did not create a table for InventoryItem in the StoreSystem database in Derby, OpenJPA
2.0 will create the table the first time an <em>"add"</em> is attempted.
	<ul>
		<li>Consider the following code:
<div class="code panel" style="border-width: 1px;"><div class="codeHeader panelHeader"
style="border-bottom-width: 1px;"><b>InventoryEntityBroker</b></div><div
class="codeContent panelContent">
<pre class="code-java">...
void addItem(<span class="code-object">String</span> name, <span class="code-object">String</span>
description, <span class="code-object">float</span> price, <span class="code-object">int</span>
categoryID)
{
    InventoryItem item = <span class="code-keyword">new</span> InventoryItem();
    item.setName(name);
    item.setDescription(description);
    ...

    em.persist(item);
}
...
</pre>
</div></div>
<p>You can then call the addItem() method in another part of the code. The EntityManager.persist()
method will throw an exception if a transaction has not been started. The transaction must
be committed by calling the Transaction.commit() method after all updates have been applied
or else the changes will not be saved to the database:</p>
<div class="code panel" style="border-width: 1px;"><div class="codeContent panelContent">
<pre class="code-java">...
em.getTransaction().begin();

addItem(...);

em.getTransaction().commit();
...
</pre>
</div></div>
		<ul>
			<li>When this is executed the first time it will use the annotations to create the
Person table, then OpenJPA 2.0 will populate it with the provided data.</li>
			<li>Note the use of the getTransaction() method to start an update and then to commit
it. The concept is the same as in any database transaction processing.</li>
			<li>Also note that while the getAllItems() function requires a JPQL SELECT query,
the update type actions have APIs.</li>
			<li>Take a look in the InventoryEntityBroker code at the addItem(), updateItem()
and deleteItem() functions and note the simplicity of these operations.</li>
		</ul>
		</li>
	</ul>
	</li>
</ul>


<ul>
	<li>An important aspect of relational databases is, of course, the relationships. The
basic relationship types are: one to many, many to one, and many to many. OpenJPA provides
annotations to identify the related fields.<br/>
Open the source file, InventoryCategory.java in Eclipse and find the following code:
<div class="code panel" style="border-width: 1px;"><div class="codeHeader panelHeader"
style="border-bottom-width: 1px;"><b>InventoryCategory.java</b></div><div
class="codeContent panelContent">
<pre class="code-java">...
@OneToMany(targetEntity=tutorial.InventoryItem.class,
   cascade=CascadeType.ALL,
   mappedBy=<span class="code-quote">"category"</span>)
<span class="code-keyword">public</span> List&lt;InventoryItem&gt; getItems()
{
    <span class="code-keyword">return</span> items;
}
...
</pre>
</div></div>
	<ul>
		<li>The annotation <font color="#646464">@OneToMany</font> identifies
that:
		<ul>
			<li>This object has a one-to-many relationship with targetEntity=tutorial.InventoryItem.class.
Meaning that one InventoryCategory can have many InventoryItems associated with it.</li>
			<li><font color="black">The property of InventoryItem that specifies the InventoryCategory
it is associated with is mappedBy="category". In other words, InventoryItem has a class property
of type InventoryCategory named "category".</font><br clear="all" />  <font
color="black">Now open the source file, InventoryItem.java and find the following code:</font>
<div class="code panel" style="border-width: 1px;"><div class="codeHeader panelHeader"
style="border-bottom-width: 1px;"><b>InventoryItem.java</b></div><div
class="codeContent panelContent">
<pre class="code-java">...
@ManyToOne
@JoinColumn(name=<span class="code-quote">"CAT_ID"</span>, nullable=<span class="code-keyword">false</span>)
<span class="code-keyword">public</span> InventoryCategory getCategory()
{
    <span class="code-keyword">return</span> category;
}
...
</pre>
</div></div></li>
			<li><font color="black">The annotation @ManyToOne identifies that:</font></li>
			<li>This object has a many-to-one relationship with the InventoryCategory object.
Meaning that there many InventoryItems can reference the same InventoryCategory</li>
		</ul>
		</li>
		<li>The annotation <font color="#646464">@JoinColumn</font> identifies
that:
		<ul>
			<li>The column in the database table that holds the InventoryCategory reference by
the attribute: <font color="black">name=</font><font color="#2a00ff">"CAT_ID"</font>.
<br clear="all" />
<div class='panelMacro'><table class='infoMacro'><colgroup><col width='24'><col></colgroup><tr><td
valign='top'><img src="/confluence/images/icons/emoticons/information.gif" width="16"
height="16" align="absmiddle" alt="" border="0"></td><td><b>Remember</b><br
/><p>These annotations contribute to the creation of the tables and the relationships.
It is important to put as much thought into how these objects relate to each other as you
would if you were designing the database tables because you are designing the database tables.<br/>
You can see more about the relationship annotations at the Apache OpenJPA site. The&nbsp;
<a href="http://openjpa.apache.org/builds/latest/docs/manual/jpa_overview_meta_field.html"
rel="nofollow">documentation is here</a>.</p></td></tr></table></div></li>
		</ul>
		</li>
	</ul>
	</li>
</ul>


<h1><a name="BeginusingOpenJPA-TheBasics-Summary"></a>Summary</h1>

<p>This was a very basic example of how to use OpenJPA with Geronimo and Derby. However,
many applications that require database persistence do not use much more than the basic functionality
demonstrated in this tutorial. The purpose of this was to be a primer. Aside from the setup
of the server and database, we went through the creation of a persistence.xml file, the basics
of the OpenJPA Entity, and EntityManager and some of the functionality.<br/>
<b><ins>Exercises</ins></b><br/>
Using this sample code as a base, try to do some of the following:</p>
<ul>
	<li>Add additional fields to the InventoryItem Entity.</li>
	<li>Create a Customer Entity and establish a one-to-many relationship with the InventoryItems
as one customer having purchased many items.</li>
	<li>Since several customers could have purchased the same items and an item could have
been purchased by many customers, use the documentation to create a many-to-many relationship
using @ManyToMany*.</li>
</ul>


<p><sub>&#42;To make these changes you may have to delete the existing database
tables so that they can recreated with the new relationship fields.</sub></p>

<p><br clear="all" /></p>

<h1><a name="BeginusingOpenJPA-TheBasics-References"></a>References</h1>

<ul>
	<li><b>Java J2SE 1.6</b>
	<ul>
		<li><a href="https://cds.sun.com/is-bin/INTERSHOP.enfinity/WFS/CDS-CDS_Developer-Site/en_US/-/USD/ViewProductDetail-Start?ProductRef=jdk-6u16-oth-JPR@CDS-CDS_Developer"
rel="nofollow">Download</a><br/>
<b>&nbsp;</b></li>
	</ul>
	</li>
	<li><b>Apache Sources</b>
	<ul>
		<li><b>Geronimo</b>
		<ul class="alternate" type="square">
			<li><a href="http://geronimo.apache.org/" rel="nofollow">Geronimo Homepage</a></li>
			<li><a href="http://cwiki.apache.org/GMOxDOC22/documentation.html" rel="nofollow">Geronimo
V2.2 Server Documentation</a></li>
			<li><a href="http://www.apache.org/dyn/closer.cgi/geronimo/2.2/geronimo-tomcat6-javaee5-2.2-bin.zip"
rel="nofollow">Geronimo V2.2 Server download</a></li>
		</ul>
		</li>
		<li><b>JPA</b>
		<ul class="alternate" type="square">
			<li><a href="http://openjpa.apache.org/" rel="nofollow">Apache OpenJPA home
page</a></li>
			<li><a href="http://openjpa.apache.org/downloads.html" rel="nofollow">Apache
OpenJPA download</a></li>
			<li><a href="http://openjpa.apache.org/documentation.html" rel="nofollow">Apache
OpenJPA        documentation</a>&nbsp;&nbsp;</li>
		</ul>
		</li>
	</ul>
	</li>
</ul>


<ul>
	<li><b>Annotations</b>
	<ul>
		<li><a href="http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html"
rel="nofollow">Documentation       for Java Annotations</a></li>
	</ul>
	</li>
	<li><b>JPQL</b>
	<ul>
		<li><a href="http://java.sun.com/javaee/5/docs/tutorial/backup/update3/doc/QueryLanguage.html"
rel="nofollow">A       reference for JPQL</a></li>
	</ul>
	</li>
	<li><b>Blogs</b>
	<ul>
		<li><a href="http://www.theserverside.com/news/thread.tss?thread_id=58343" rel="nofollow">Discussion
      on The Server Side</a></li>
		<li><a href="http://bit.ly/WASJPAblog" rel="nofollow">Websphere &amp; OpenJPA
blog on       blogspot</a></li>
		<li><a href="http://bit.ly/JPATutApachedwBlog" rel="nofollow">JPA Blog on developerWorks</a></li>
	</ul>
	</li>
	<li><b>Implementation Sites</b>
	<ul>
		<li><a href="http://bit.ly/BetaSiteApache" rel="nofollow">IBM WebSphere Application
Server V7 Java Persistence API (JPA) 2.0 Open Beta</a></li>
	</ul>
	</li>
</ul>

     </div>
     <div id="commentsSection" class="wiki-content pageSection">
       <div style="float: right;">
            <a href="http://cwiki.apache.org/confluence/users/viewnotifications.action"
class="grey">Change Notification Preferences</a>
       </div>

       <a href="http://cwiki.apache.org/confluence/display/openjpa/Begin+using+OpenJPA+-+The+Basics">View
Online</a>
       |
       <a href="http://cwiki.apache.org/confluence/pages/diffpagesbyversion.action?pageId=12320826&revisedVersion=10&originalVersion=9">View
Change</a>
              |
       <a href="http://cwiki.apache.org/confluence/display/openjpa/Begin+using+OpenJPA+-+The+Basics?showComments=true&amp;showCommentArea=true#addcomment">Add
Comment</a>
            </div>
</div>
</div>
</div>
</div>
</body>
</html>

Mime
View raw message