<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>The JavaDude Weblog &#187; jpa</title>
	<atom:link href="http://javadude.wordpress.com/tag/jpa/feed/" rel="self" type="application/rss+xml" />
	<link>http://javadude.wordpress.com</link>
	<description>Jabbering about Java Development and whatever comes along. JavaFX &#124; Android &#124; Glassfish &#124; Netbeans &#124; JEE5</description>
	<lastBuildDate>Sat, 02 Jan 2010 18:27:27 +0000</lastBuildDate>
	<generator>http://wordpress.com/</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<cloud domain='javadude.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://www.gravatar.com/blavatar/7b8f0e95aa26ed236a7773266bdd2ea7?s=96&#038;d=http://s.wordpress.com/i/buttonw-com.png</url>
		<title>The JavaDude Weblog &#187; jpa</title>
		<link>http://javadude.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://javadude.wordpress.com/osd.xml" title="The JavaDude Weblog" />
		<item>
		<title>Interacting with Databases through the Java Persistence API</title>
		<link>http://javadude.wordpress.com/2009/04/25/interacting-with-databases-through-the-java-persistence-api/</link>
		<comments>http://javadude.wordpress.com/2009/04/25/interacting-with-databases-through-the-java-persistence-api/#comments</comments>
		<pubDate>Sat, 25 Apr 2009 03:05:13 +0000</pubDate>
		<dc:creator>devdude</dc:creator>
				<category><![CDATA[netbeans]]></category>
		<category><![CDATA[tutorial]]></category>
		<category><![CDATA[jpa]]></category>
		<category><![CDATA[pojo]]></category>

		<guid isPermaLink="false">http://javadude.wordpress.com/?p=534</guid>
		<description><![CDATA[Featured article about working with JPA in Netbeans. Reviewed and reproduced following an article by PACKT Publishing (link). Please hava a look at the end of the article with the book recommendation.
We will look into:






Creating our first JPA entity
Interacting with JPA entities with entity manager
Generating forms in JSF pages from JPA entities
Generating JPA entities from [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javadude.wordpress.com&blog=3891833&post=534&subd=javadude&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>Featured article about working with JPA in Netbeans. Reviewed and reproduced following an article by PACKT Publishing (<a href="http://www.packtpub.com" target="_blank">link</a>). Please hava a look at the end of the article with the book recommendation.</p>
<p>We will look into:</p>
<table style="height:91px;" border="0" cellspacing="0" cellpadding="0" width="1079">
<tbody>
<tr>
<td width="99" valign="top"><a href="http://www.packtpub.com/java-ee5-development-with-netbeans-6/book"><img class="left" title="Java EE 5 Development with NetBeans 6" src="http://images.packtpub.com/images/100x123/1847195466.png" border="0" alt="Java EE 5 Development with NetBeans 6" width="99" height="123" /></a></td>
<td valign="top">
<ul>
<li>Creating our first JPA entity</li>
<li>Interacting with JPA entities with entity manager</li>
<li>Generating forms in JSF pages from JPA entities</li>
<li>Generating JPA entities from an existing database schema</li>
<li>JPA named queries and JPQL</li>
<li>Entity relationships</li>
<li>Generating complete JSF applications from JPA entities</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p><span id="more-534"></span></p>
<h1>Creating Our First JPA Entity</h1>
<p>JPA entities are Java classes whose fields are persisted to a database by the JPA API. JPA entities are <strong>Plain Old Java Objects (POJOs)</strong>, as such, they don&#8217;t need to extend any specific parent class or implement any specific interface. A Java class is designated as a JPA entity by decorating it with the @Entity annotation.</p>
<p>In order to create and test our first JPA entity, we will be creating a new web application using the JavaServer Faces framework. In this example we will name our application <strong>jpaweb</strong>. As with all of our examples, we will be using the bundled GlassFish application server.</p>
<p>To create a new JPA Entity, we need to right-click on the project and select <strong>New | Entity Class</strong>.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%201.png" alt="" /></p>
<p>After doing so, NetBeans presents the <strong>New Entity Class</strong> wizard.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%202.png" alt="" /></p>
<p>At this point, we should specify the values for the <strong>Class Name</strong> and <strong>Package</strong> fields (<strong>Customer</strong> and <strong>com.ensode.jpaweb</strong> in our example), then click on the <strong>Create Persistence Unit&#8230;</strong> button.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%203.png" alt="" /></p>
<p>The <strong>Persistence Unit Name</strong> field is used to identify the persistence unit that will be generated by the wizard, it will be defined in a JPA configuration file named persistence.xml that NetBeans will automatically generate from the <strong>Create Persistence Unit</strong> wizard. The <strong>Create Persistence Unit</strong> wizard will suggest a name for our persistence unit, in most cases the default can be safely accepted.</p>
<p>JPA is a specification for which several implementations exist. NetBeans supports several JPA implementations including Toplink, Hibernate, KODO, and OpenJPA. Since the bundled GlassFish application server includes Toplink as its default JPA implementation, it makes sense to take this default value for the <strong>Persistence Provider</strong> field when deploying our application to GlassFish.</p>
<p>Before we can interact with a database from any Java EE 5 application, a database connection pool and data source need to be created in the application server.</p>
<p>A database connection pool contains connection information that allow us to connect to our database, such as the server name, port, and credentials. The advantage of using a connection pool instead of directly opening a JDBC connection to a database is that database connections in a connection pool are never closed, they are simply allocated to applications as they need them. This results in performance improvements, since the operations of opening and closing database connections are expensive in terms of performance.</p>
<p>Data sources allow us to obtain a connection from a connection pool by obtaining an instance of <em>javax.sql.DataSource</em> via JNDI, then invoking its <em>getConnection()</em> method to obtain a database connection from a connection pool. When dealing with JPA, we don&#8217;t need to directly obtain a reference to a data source, it is all done automatically by the JPA API, but we still need to indicate the data source to use in the application&#8217;s Persistence Unit.</p>
<p>NetBeans comes with a few data sources and connection pools pre-configured. We could use one of these pre-configured resources for our application, however, NetBeans also allows creating these resources &#8220;on the fly&#8221;, which is what we will be doing in our example.</p>
<p>To create a new data source we need to select the <strong>New Data Source&#8230;</strong> item from the <strong>Data Source</strong> combo box.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%204.png" alt="" /></p>
<p>A data source needs to interact with a database connection pool. NetBeans comes pre-configured with a few connection pools out of the box, but just like with data sources, it allows us to create a new connection pool &#8220;on demand&#8221;. In order to do this, we need to select the <strong>New Database Connection&#8230;</strong> item from the <strong>Database Connection</strong> combo box.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%205.png" alt="" /></p>
<p>NetBeans includes JDBC drivers for a few <strong>Relational Database Management Systems (RDBMS)</strong> such as JavaDB, MySQL, and PostgreSQL &#8220;out of the box&#8221;. JavaDB is bundled with both GlassFish and NetBeans, therefore we picked JavaDB for our example. This way we avoid having to install an external RDBMS.</p>
<p style="margin-left:40px;margin-right:40px;"><em>For RDBMS systems that are not supported out of the box, we need to obtain a JDBC driver and let NetBeans know of it&#8217;s location by selecting New Driver from the Name combo box. We then need to navigate to the location of a JAR file containing the JDBC driver. Consult your RDBMS documentation for details.</em></p>
<p>JavaDB is installed in our workstation, therefore the server name to use is <em>localhost</em>. By default, JavaDB listens to port <em>1527</em>, therefore that is the port we specify in the URL. We wish to connect to a database called <em>jpaintro</em>, therefore we specify it as the database name. Since the <em>jpaintro</em> database does not exist yet, we pass the attribute <em>create=true</em> to JavaDB, this attribute is used to create the database if it doesn&#8217;t exist yet.</p>
<p>Every JavaDB database contains a schema named APP, since each user by default uses a schema named after his/her own login name. The easiest way to get going is to create a user named &#8220;APP&#8221; and select a password for this user.</p>
<p>Clicking on the <strong>Show JDBC URL</strong> checkbox reveals the JDBC URL for the connection we are setting up.</p>
<p style="margin-left:40px;margin-right:40px;"><em>The New Database Connection wizard warns us of potential security risks when choosing to let NetBeans remember the password for the database connection. Database passwords are scrambled (but not encrypted) and stored in an XML file under the .netbeans/[netbeans version]/config/Databases/Connections directory. If we follow common security practices such as locking our workstation when we walk away from it, the risks of having NetBeans remember database passwords will be minimal.</em></p>
<p>Once we have created our new data source and connection pool, we can continue configuring our persistence unit.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%206.png" alt="" /></p>
<p>It is a good idea to leave the <strong>Use Java Transaction APIs</strong> checkbox checked. This will instruct our JPA implementation to use the <strong>Java Transaction API (JTA)</strong> to allow the application server to manage transactions. If we uncheck this box, we will need to manually write code to manage transactions.</p>
<p>Most JPA implementations allow us to define a table generation strategy. We can instruct our JPA implementation to create tables for our entities when we deploy our application, to drop the tables then regenerate them when our application is deployed, or not create any tables at all. NetBeans allows us to specify the table generation strategy for our application by clicking the appropriate value in the <strong>Table Generation Strategy</strong> radio button group.</p>
<p style="margin-left:40px;margin-right:40px;"><em>When working with a new application, it is a good idea to select the Drop and Create table generation strategy. This will allow us to add, remove, and rename fields in our JPA entity at will without having to make the same changes in the database schema. When selecting this table generation strategy, tables in the database schema will be dropped and recreated, therefore any data previously persisted will be lost.</em></p>
<p>Once we have created our new data source, database connection and persistence unit, we are ready to create our new JPA entity.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%207.png" alt="" /></p>
<p>We can do so by simply clicking on the <strong>Finish</strong> button. At this point NetBeans generates the source for our JPA entity.</p>
<p style="margin-left:40px;margin-right:40px;"><em>JPA allows the primary field of a JPA entity to map to any column type (VARCHAR, NUMBER). It is best practice to have a numeric surrogate primary key, that is, a primary key that serves only as an identifier and has no business meaning in the application. Selecting the default Primary Key type of long will allow for a wide range of values to be available for the primary keys of our entities.</em></p>
<pre style="margin-left:40px;">package com.ensode.jpaweb;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
public void setId(Long id) {
this.id = id;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
//Other generated methods (hashCode(), equals() and
//toString() omitted for brevity.
}</pre>
<p>As we can see, a JPA entity is a standard Java object. There is no need to extend any special class or implement any special interface. What differentiates a JPA entity from other Java objects are a few JPA-specific annotations.</p>
<p>The @Entity annotation is used to indicate that our class is a JPA entity. Any object we want to persist to a database via JPA must be annotated with this annotation.</p>
<p>The @Id annotation is used to indicate what field in our JPA entity is its primary key. The primary key is a unique identifier for our entity. No two entities may have the same value for their primary key field. This annotation can be placed just above the getter method for the primary key class. This is the strategy that the NetBeans wizard follows. It is also correct to specify the annotation right above the field declaration.</p>
<p>The @Entity and the @Id annotations are the bare minimum two annotations that a class needs in order to be considered a JPA entity. JPA allows primary keys to be automatically generated. In order to take advantage of this functionality, the @GeneratedValue annotation can be used. As we can see, the NetBeans generated JPA entity uses this annotation. This annotation is used to indicate the strategy to use to generate primary keys. All possible primary key generation strategies are listed in the following table:</p>
<p style="text-align:center;">
<div>
<table class="MsoTableGrid" style="border:medium none;border-collapse:collapse;width:621px;height:478px;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="border:1pt solid black;padding:0 5.4pt;" valign="top">
<p class="Pa45" style="text-align:center;"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN"> </span></p>
<table class="MsoNormalTable" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height:12.9pt;">
<td style="border:medium none;height:12.9pt;padding:0 5.4pt;" valign="top">
<p class="Pa35"><strong><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN">Primary Key Generation Strategy</span></strong></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;">
</td>
<td style="border:1pt 1pt 1pt medium solid solid solid none black black black 0;padding:0 5.4pt;" valign="top">
<p class="Pa45"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN"> </span></p>
<table class="MsoNormalTable" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height:12.9pt;">
<td style="border:medium none;height:12.9pt;padding:0 5.4pt;" valign="top">
<p class="Pa35" style="text-align:center;"><strong><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN">Description</span></strong></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;">
</td>
</tr>
<tr>
<td style="border:medium 1pt 1pt none solid solid 0 black black;padding:0 5.4pt;" valign="top">
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:12.05pt;"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN"> </span></p>
<table class="MsoNormalTable" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height:10.5pt;">
<td style="border:medium none;height:10.5pt;padding:0 5.4pt;" valign="top">
<p class="MsoNormal" style="margin-bottom:.0001pt;"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN">GenerationType.AUTO</span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;">
</td>
<td style="border:medium 1pt 1pt medium none solid solid none 0 black black 0;padding:0 5.4pt;" valign="top">
<p class="Pa45"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN"> </span></p>
<table class="MsoNormalTable" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height:46.95pt;">
<td style="border:medium none;height:46.95pt;padding:0 5.4pt;" valign="top">
<p class="Pa35"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN">Indicates that the persistence provider will automatically select a primary key generation strategy. Used by default if no primary key generation strategy is specified.</span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;">
</td>
</tr>
<tr>
<td style="border:medium 1pt 1pt none solid solid 0 black black;padding:0 5.4pt;" valign="top">
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:12.05pt;"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN"> </span></p>
<table class="MsoNormalTable" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height:10.5pt;">
<td style="border:medium none;height:10.5pt;padding:0 5.4pt;" valign="top">
<p class="MsoNormal" style="margin-bottom:.0001pt;"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN">GenerationType.IDENTITY</span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;">
</td>
<td style="border:medium 1pt 1pt medium none solid solid none 0 black black 0;padding:0 5.4pt;" valign="top">
<p class="Pa45"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN"> </span></p>
<table class="MsoNormalTable" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height:35.55pt;">
<td style="border:medium none;height:35.55pt;padding:0 5.4pt;" valign="top">
<p class="Pa35"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN">Indicates that an identity column in the database table the JPA entity maps to must be used to generate the primary key value.</span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;">
</td>
</tr>
<tr>
<td style="border:medium 1pt 1pt none solid solid 0 black black;padding:0 5.4pt;" valign="top">
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:12.05pt;"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN"> </span></p>
<table class="MsoNormalTable" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height:10.5pt;">
<td style="border:medium none;height:10.5pt;padding:0 5.4pt;" valign="top">
<p class="MsoNormal" style="margin-bottom:.0001pt;"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN">GenerationType.SEQUENCE</span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;">
</td>
<td style="border:medium 1pt 1pt medium none solid solid none 0 black black 0;padding:0 5.4pt;" valign="top">
<p class="Pa45"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN"> </span></p>
<table class="MsoNormalTable" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height:35.55pt;">
<td style="border:medium none;height:35.55pt;padding:0 5.4pt;" valign="top">
<p class="Pa35"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN">Indicates that a database sequence should be used to generate the entity&#8217;s primary key value.</span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;">
</td>
</tr>
<tr>
<td style="border:medium 1pt 1pt none solid solid 0 black black;padding:0 5.4pt;" valign="top">
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:12.05pt;"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN"> </span></p>
<table class="MsoNormalTable" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height:10.5pt;">
<td style="border:medium none;height:10.5pt;padding:0 5.4pt;" valign="top">
<p class="MsoNormal" style="margin-bottom:.0001pt;"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN">GenerationType.TABLE</span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;">
</td>
<td style="border:medium 1pt 1pt medium none solid solid none 0 black black 0;padding:0 5.4pt;" valign="top">
<p class="Pa45"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN"> </span></p>
<table class="MsoNormalTable" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height:24.15pt;">
<td style="border:medium none;height:24.15pt;padding:0 5.4pt;" valign="top">
<p class="Pa35"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN">Indicates that a database table should be used to generate the entity&#8217;s primary key value.</span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;">
</td>
</tr>
</tbody>
</table>
</div>
<p>In most cases, the <em>GenerationType.AUTO</em> strategy works properly, therefore it is almost always used. For this reason the <strong>New Entity Class</strong> wizard uses this strategy.</p>
<p style="margin-left:40px;margin-right:40px;"><em>When using the sequence or table generation strategies, we might have to indicate the sequence or table used to generate the primary keys. These can be specified by using the @SequenceGenerator and @TableGenerator annotations, respectively. Consult the Java EE 5 JavaDoc at <a href="http://java.sun.com/javaee/5/docs/api/" target="_blank">http://java.sun.com/javaee/5/docs/api/</a> for details.</em></p>
<p>For further knowledge on primary key generation strategies you can refer <em>EJB 3 Developer Guide</em> by <strong>Michael Sikora</strong>, which is another book by Packt Publishing (<a href="http://www.packtpub.com/developer-guide-for-ejb3/book/sl/javaee-abr/1108" target="_blank">http://www.packtpub.com/developer-guide-for-ejb3/book</a>).</p>
<h2>Adding Persistent Fields to Our Entity</h2>
<p>At this point, our JPA entity contains a single field, its primary key. Admittedly not very useful, we need to add a few fields to be persisted to the database.</p>
<pre style="margin-left:40px;">package com.ensode.jpaweb;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String firstName;
private String lastName;
public void setId(Long id) {
this.id = id;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
//Additional methods omitted for brevity
}</pre>
<p>In this modified version of our JPA entity, we added two fields to be persisted to the database; firstName will be used to store the user&#8217;s first name, lastName will be used to store the user&#8217;s last name. JPA entities need to follow standard JavaBean coding conventions. This means that they must have a public constructor that takes no arguments (one is automatically generated by the Java compiler if we don&#8217;t specify any other constuctors), and all fields must be private, and accessed through getter and setter methods.</p>
<p style="margin-left:40px;margin-right:40px;"><em><strong>Automatically Generating Getters and Setters</strong><br />
In NetBeans, getter and setter methods can be generated automatically. Simply declare new fields as usual then use the &#8220;insert code&#8221; keyboard shortcut (default is Alt+Insert), then select Getter and Setter from the resulting pop-up window, then click on the check box next to the class name to select all fields, then click on the Generate button.</em></p>
<p>Before we can use JPA persist our entity&#8217;s fields into our database, we need to write some additional code.</p>
<h2>Creating a Data Access Object (DAO)</h2>
<p>It is a good idea to follow the DAO design pattern whenever we write code that interacts with a database. The DAO design pattern keeps all database access functionality in DAO classes. This has the benefit of creating a clear separation of concerns, leaving other layers in our application, such as the user interface logic and the business logic, free of any persistence logic.</p>
<p>There is no special procedure in NetBeans to create a DAO. We simply follow the standard procedure to create a new class by selecting <strong>File | New</strong>, then selecting <strong>Java</strong> as the category and the <strong>Java Class</strong> as the file type, then entering a name and a package for the class. In our example, we will name our class <em>CustomerDAO</em> and place it in the <em>com.ensode.jpaweb</em> package.</p>
<p>At this point, NetBeans create a very simple class containing only the package and class declarations.</p>
<p>To take complete advantage of Java EE features such as dependency injection, we need to make our DAO a JSF managed bean. This can be accomplished by simply opening <em>faces-config.xml</em>, clicking its <strong>XML</strong> tab, then right-clicking on it and selecting <strong>JavaServer Faces | Add Managed Bean</strong>.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%208.png" alt="" /></p>
<p>We get the <strong>Add Manged Bean</strong> dialog as seen here:</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%209.png" alt="" /></p>
<p>We need to enter a name, fully qualified name, and scope for our managed bean (which, in our case, is our DAO), then click on the <strong>Add</strong> button.</p>
<p>This action results in our DAO being declared as a managed bean in our application&#8217;s <em>faces-config.xml</em> configuration file.</p>
<pre style="margin-left:40px;">&lt;managed-bean&gt;
&lt;managed-bean-name&gt;CustomerDAO&lt;/managed-bean-name&gt;
&lt;managed-bean-class&gt;
com.ensode.jpaweb.CustomerDAO
&lt;/managed-bean-class&gt;
&lt;managed-bean-scope&gt;session&lt;/managed-bean-scope&gt;
&lt;/managed-bean&gt;</pre>
<p>We could at this point start writing our JPA code manually, but with NetBeans there is no need to do so, we can simply right-click on our code and select <strong>Persistence | Use Entity Manager</strong>, and most of the work is automatically done for us.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%2010.png" alt="" /></p>
<p>Here is how our code looks like after doing this trivial procedure:</p>
<pre style="margin-left:40px;">package com.ensode.jpaweb;
import javax.annotation.Resource;
import javax.naming.Context;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
@PersistenceContext(name = "persistence/LogicalName",
unitName = "jpawebPU")
public class CustomerDAO {
@Resource
private javax.transaction.UserTransaction utx;
protected void persist(Object object) {
try {
Context ctx =
(Context) new javax.naming.InitialContext().
lookup("java:comp/env");
utx.begin();
EntityManager em = (EntityManager)
ctx.lookup("persistence/LogicalName");
em.persist(object);
utx.commit();
} catch (Exception e) {
java.util.logging.Logger.getLogger(
getClass().getName()).log(
java.util.logging.Level.SEVERE,
"exception caught", e);
throw new RuntimeException(e);
}
}
}</pre>
<p>All highlighted code is automatically generated by NetBeans. The main thing NetBeans does here is add a method that will automatically insert a new row in the database, effectively persisting our entity&#8217;s properties.</p>
<p>As we can see, NetBeans automatically generates all necessary import statements. Additionally, our new class is automatically decorated with the @PersistenceContext annotation. This annotation allows us to declare that our class depends on an EntityManager (we&#8217;ll discuss EntityManager in more detail shortly). The value of its name attribute is a logical name we can use when doing a JNDI lookup for our EntityManager. NetBeans by default uses persistence/LogicalName as the value for this property.</p>
<p style="margin-left:40px;margin-right:40px;"><em>The Java Naming and Directory Interface (JNDI) is an API we can use to obtain resources, such as database connections and JMS queues, from a directory service.</em></p>
<p>The value of the unitName attribute of the @PersistenceContext annotation refers to the name we gave our application&#8217;s Persistence Unit.</p>
<p>NetBeans also creates a new instance variable of type <em>javax.transaction.UserTransaction</em>. This variable is needed since all JPA code must be executed in a transaction. UserTransaction is part of the <strong>Java Transaction API (JTA)</strong>. This API allows us to write code that is transactional in nature. Notice that the UserTransaction instance variable is decorated with the @Resource annotation. This annotation is used for <strong>dependency injection</strong>. in this case an instance of a class of type <em>javax.transaction.UserTransaction</em> will be instantiated automatically at run-time, without having to do a JNDI lookup or explicitly instantiating the class.</p>
<p style="margin-left:40px;margin-right:40px;"><em>Dependency injection is a new feature of Java EE 5 not present in previous versions of J2EE, but that was available and made popular in the Spring framework. With standard J2EE code, it was necessary to write boilerplate JNDI lookup code very frequently in order to obtain resources. To alleviate this situation, Java EE 5 made dependency injection part of the standard.</em></p>
<p>The next thing we see is that NetBeans added a persist method that will persist a JPA entity, automatically inserting a new row containing our entity&#8217;s fields into the database. As we can see, this method takes an instance of <em>java.lang.Object</em> as its single parameter. The reason for this is that the method can be used to persist any JPA entity (although in our example, we will use it to persist only instances of our Customer entity).</p>
<p>The first thing the generated method does is obtain an instance of <em>javax.naming.InitialContext</em> by doing a JNDI lookup on <em>java:comp/env</em>. This JNDI name is the root context for all Java EE 5 components.</p>
<p>The next thing the method does is initiate a transaction by invoking <em>uxt.begin()</em>. Notice that since the value of the utx instance variable was injected via dependency injection (by simply decorating its declaration with the @Resource annotation), there is no need to initialize this variable.</p>
<p>Next, the method does a JNDI lookup to obtain an instance of <em>javax.persistence.EntityManager</em>. This class contains a number of methods to interact with the database. Notice that the JNDI name used to obtain an EntityManager matches the value of the name attribute of the @PersistenceContext annotation.</p>
<p>Once an instance of EntityManager is obtained from the JNDI lookup, we persist our entity&#8217;s properties by simply invoking the <em>persist()</em> method on it, passing the entity as a parameter to this method. At this point, the data in our JPA entity is inserted into the database.</p>
<p>In order for our database insert to take effect, we must commit our transaction, which is done by invoking <em>utx.commit()</em>.</p>
<p>It is always a good idea to look for exceptions when dealing with JPA code. The generated method does this, and if an exception is caught, it is logged and a RuntimeException is thrown. Throwing a RuntimeException has the effect of rolling back our transaction automatically, while letting the invoking code know that something went wrong in our method. The UserTransaction class has a <em>rollback()</em> method that we can use to roll back our transaction without having to throw a RunTimeException.</p>
<p>At this point we have all the code we need to persist our entity&#8217;s properties in the database. Now we need to write some additional code for the user interface part of our application. NetBeans can generate a rudimentary JSF page that will help us with this task.</p>
<h2>Generating the User Interface</h2>
<p>To have NetBeans automatically generate the user interface, first we need to create a new JSP as usual, by right-clicking on the project, selecting <strong>New | JSP</strong>, then entering a name for our JSP in the <strong>New JSP File</strong> wizard. At this point, the generated markup for the new JSP will look like this:</p>
<pre style="margin-left:40px;">&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;
&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;
&lt;title&gt;JSP Page&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Hello World!&lt;/h1&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
<p>Once we have our JSP, we can drag the <strong>JSF Form</strong> element from the NetBeans palette into our markup, then select <strong>Form Generated From Entity Class</strong>, enter the fully qualified name for our JPA entity, then select <strong>Editable</strong> in the <strong>Form Fields</strong> radio buttons.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%2011.png" alt="" /></p>
<p>After adding the generated markup, we need to manually add the standard JSF <em>&lt;%@ taglib%&gt;</em> elements to our page. After modifying the generated title and deleting the  and deleting the <em>&lt;h2&gt;</em> tag generated by the <strong>New JSP File</strong> wizard, our page markup now looks like this:</p>
<pre style="margin-left:40px;">&lt;%@page contentType="text/html" pageEncoding="UTF-8"%&gt;
&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"&gt;
&lt;%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %&gt;
&lt;%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %&gt;
&lt;html&gt;
&lt;head&gt;
&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;
&lt;title&gt;Insert Customer&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;f:view&gt;
&lt;h2&gt;Create&lt;/h2&gt;
&lt;h:form&gt;
&lt;h:panelGrid columns="2"&gt;
&lt;h:outputText value="FirstName:"/&gt;
&lt;h:inputText id="firstName"
value="#{anInstanceOfcom.ensode.jpaweb.Customer. firstName}"
title="FirstName" /&gt;
&lt;h:outputText value="LastName:"/&gt;
&lt;h:inputText id="lastName" value="#{anInstanceOfcom.ensode.jpaweb. Customer.lastName}"
title="LastName" /&gt;
&lt;/h:panelGrid&gt;
&lt;/h:form&gt;
&lt;/f:view&gt;
&lt;/body&gt;
&lt;/html&gt;</pre>
<p>Notice that NetBeans automatically inserts JSF complete with value binding expressions mapping to our entity&#8217;s properties. It uses a temporary placeholder managed bean name to access our entity. In our example, the generated managed bean name is <em>anInstanceOfcom.ensode.jpaweb.Customer</em>. In general, the generated managed bean name will be the fully qualified name of the bean&#8217;s class, prefixed by <em>anInstanceOf</em>. Before this code can work, we need to make our JPA entity a JSF managed bean following the same procedure we used for the DAO.</p>
<p>In order to be able to persist the user-entered data, we need to make a few modifications to the generated markup in our JSP.</p>
<pre style="margin-left:40px;">&lt;h:form&gt;
&lt;h:panelGrid columns="2"&gt;
&lt;h:outputText value="FirstName:"/&gt;
&lt;h:inputText id="firstName"
value="#{Customer.firstName}" title="FirstName" /&gt;
&lt;h:outputText value="LastName:"/&gt;
&lt;h:inputText id="lastName" value="#{Customer.lastName}"
title="LastName" /&gt;
&lt;h:panelGroup/&gt;
&lt;h:commandButton value="Submit"
action="#{Controller.saveCustomer}"/&gt;
&lt;/h:panelGrid&gt;
&lt;/h:form&gt;</pre>
<p>The first thing we need to do is modify the value binding expression of the generated <em>&lt;h:inputText&gt;</em> elements to match the name we gave our JPA entity in <em>faces-config.xml</em> (Customer, in our case), then we need to add a command button so that our page will be submitted.</p>
<h2>Implementing the Controller</h2>
<p>At this point, we have the presentation layer (View) of our application ready, as well as the data access layer (Model), the only thing missing is to add a controller to complete the third layer of our application, which will follow the MVC design pattern.</p>
<pre style="margin-left:40px;">package com.ensode.jpaweb;
public class Controller {
private CustomerDAO customerDAO;
private Customer customer;
public CustomerDAO getCustomerDAO() {
return customerDAO;
}
public void setCustomerDAO(CustomerDAO customerDAO) {
this.customerDAO = customerDAO;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public String saveCustomer() {
String returnVal;
try {
customerDAO.persist(customer);
returnVal = "success";
} catch (Exception e) {
returnVal = "failure";
e.printStackTrace();
}
System.out.println(this.getClass().getName() + ".saveCustomer()nreturnVal = " + returnVal);
return returnVal;
}
}</pre>
<p>Our controller has a <em>saveCustomer()</em> method that will be invoked when the user clicks on the <strong>Submit</strong> button on the page, the method simply invokes the <em>persist()</em> method on the DAO, then uses standard JSF navigation to go to a confirmation page if everything went fine, or to an error page if an exception was thrown.</p>
<p>Notice the Controller class has two instance variables for our JPA entity and our DAO. There is no need for us to explicitly instantiate these variables, instead we can use a JSF feature called <strong>managed properties</strong>. Managed properties are injected at runtime by using dependency injection. In order to configure this the application&#8217;s faces-config.xml needs to be modified.</p>
<pre style="margin-left:40px;">&lt;managed-bean&gt;
&lt;managed-bean-name&gt;CustomerDAO&lt;/managed-bean-name&gt;
&lt;managed-bean-class&gt;
com.ensode.jpaweb.CustomerDAO
&lt;/managed-bean-class&gt;
&lt;managed-bean-scope&gt;session&lt;/managed-bean-scope&gt;
&lt;/managed-bean&gt;
&lt;managed-bean&gt;
&lt;managed-bean-name&gt;Customer&lt;/managed-bean-name&gt;
&lt;managed-bean-class&gt;
com.ensode.jpaweb.Customer
&lt;/managed-bean-class&gt;
&lt;managed-bean-scope&gt;request&lt;/managed-bean-scope&gt;
&lt;/managed-bean&gt;
&lt;managed-bean&gt;
&lt;managed-bean-name&gt;Controller&lt;/managed-bean-name&gt;
&lt;managed-bean-class&gt;
com.ensode.jpaweb.Controller
&lt;/managed-bean-class&gt;
&lt;managed-bean-scope&gt;request&lt;/managed-bean-scope&gt;
&lt;managed-property&gt;
&lt;property-name&gt;customerDAO&lt;/property-name&gt;
&lt;property-class&gt;
com.ensode.jpaweb.CustomerDAO
&lt;/property-class&gt;
&lt;value&gt;#{CustomerDAO}&lt;/value&gt;
&lt;/managed-property&gt;
&lt;managed-property&gt;
&lt;property-name&gt;customer&lt;/property-name&gt;
&lt;property-class&gt;
com.ensode.jpaweb.Customer
&lt;/property-class&gt;
&lt;value&gt;#{Customer}&lt;/value&gt;
&lt;/managed-property&gt;
&lt;/managed-bean&gt;</pre>
<p>The <em>&lt;managed-property&gt;</em> element is used to define our managed properties. The <em>&lt;property-name&gt;</em> element is used to indicate the managed property name; the value of this element must match the name of the property in the managed bean&#8217;s code (in our example, both the <em>customer</em> and <em>customerDAO</em> properties are managed properties). The value of the <em>&lt;property-class&gt;</em> element must be the fully qualified name of the property type, and the value of the <em>&lt;value&gt;</em> attribute must match the value of the <em>&lt;managed-bean-name&gt;</em> element for managed beans used to populate managed properties. In our example, our JPA entity is declared as a managed bean, using a value of Customer as its logical name, which matches the value binding expression of <em>#{Customer}</em> used to populate the customer managed property of our controller. In order to have the <em>customerDAO</em> property populated at runtime, our <em>CustomerDAO</em> class needs to be added as a managed bean like we previously did for the Customer class.</p>
<h2>Trying Out Our Application</h2>
<p>At this point, we have a complete, albeit simple, application that will gather input from the user, populate a JPA entity from this input, and save the data to the database. We can execute our application by right-clicking on the project and selecting <strong>Run</strong>.</p>
<p>At this point the application server is started if it wasn&#8217;t running already, our application is deployed and a new window of the default web browser is automatically opened, pointing to the URL of our application. After entering some data into the input fields, our page looks like:</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%2012.png" alt="" /></p>
<p style="margin-left:40px;margin-right:40px;"><em>Notice that the labels for the fields aren&#8217;t very user-friendly. Recall that this page was almost completely generated from our JPA entity bean. By default, NetBeans uses the property name as the label for each field. We are free, of course, to modify these labels to make them more readable for our users.</em></p>
<p>After clicking the <strong>Submit</strong> button, our data is saved to the database and we are directed to a confirmation screen.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%2013.png" alt="" /></p>
<p>If we inspect our database schema, we can see that a CUSTOMER table was created automatically, since we used the <strong>Drop and Create</strong> Table generation strategy. Additionally, a new row was inserted when we clicked on the <strong>Submit</strong> button.</p>
<p>We can inspect the database schema by going to the <strong>Services</strong> tab, right-clicking on our schema (<strong>jpaintro</strong>), then selecting <strong>Connect</strong>. Expanding the <strong>Tables</strong> node reveals the newly created <strong>CUSTOMER</strong>.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%2014.png" alt="" /></p>
<p>We can view the data in the table by right-clicking on it and selecting <strong>View Data</strong>. At this point a new <strong>SQL Command</strong> window is opened and an SQL query retrieving all the data in our table is automatically executed.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%2015.png" alt="" /></p>
<p>As we have seen, NetBeans makes it easy to write code that inserts rows into a database table by generating JPA code.</p>
<p>If we need to add additional functionality such as retrieving, updating, or deleting data, we would need to write additional methods in our DAO. The DAO would invoke corresponding methods on EntityManager. The following table lists some of the most commonly used methods on EntityManager.</p>
<p style="text-align:center;">
<div>
<table class="MsoTableGrid" style="border:medium none;border-collapse:collapse;width:631px;height:519px;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td style="border:1pt solid black;padding:0 5.4pt;" valign="top">
<p class="Pa45"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN"> </span></p>
<table class="MsoNormalTable" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height:12.9pt;">
<td style="border:medium none;height:12.9pt;padding:0 5.4pt;" valign="top">
<p class="Pa35"><strong><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN">EntityManager method</span></strong></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;">
</td>
<td style="width:128.05pt;padding:0 5.4pt;" width="171" valign="top">
<p class="Pa45"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN"> </span></p>
<table class="MsoNormalTable" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height:12.9pt;">
<td style="border:medium none;height:12.9pt;padding:0 5.4pt;" valign="top">
<p class="Pa35"><strong><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN">Description</span></strong></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;">
</td>
<td style="width:114.25pt;padding:0 5.4pt;" width="152" valign="top">
<p class="Pa45"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN"> </span></p>
<table class="MsoNormalTable" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height:12.9pt;">
<td style="border:medium none;height:12.9pt;padding:0 5.4pt;" valign="top">
<p class="Pa35"><strong><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN">Example</span></strong></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;">
</td>
</tr>
<tr>
<td style="border:medium 1pt 1pt none solid solid 0 black black;padding:0 5.4pt;" valign="top">
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:12.05pt;"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN"> </span></p>
<table class="MsoNormalTable" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height:33.3pt;">
<td style="border:medium none;height:33.3pt;padding:0 5.4pt;" valign="top">
<p class="MsoNormal" style="margin-bottom:.0001pt;"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN">&lt;T&gt; T find(Class&lt;T&gt; entityClass, Object primaryKey)</span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;">
</td>
<td style="width:128.05pt;padding:0 5.4pt;" width="171" valign="top">
<p class="Pa45"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN"> </span></p>
<table class="MsoNormalTable" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height:92.55pt;">
<td style="border:medium none;height:92.55pt;padding:0 5.4pt;" valign="top">
<p class="Pa35"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN">Retrieves a row of data matching the supplied primary key from the database table our JPA entity maps to. The first parameter must be the class of our JPA entity, the second parameter must be the primary key. </span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;">
</td>
<td style="width:114.25pt;padding:0 5.4pt;" width="152" valign="top">
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:12.05pt;"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN"> </span></p>
<table class="MsoNormalTable" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height:33.3pt;">
<td style="border:medium none;height:33.3pt;padding:0 5.4pt;" valign="top">
<p class="MsoNormal" style="margin-bottom:.0001pt;"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN">customer = em.find(Customer.class, new Long(2));</span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;">
</td>
</tr>
<tr>
<td style="border:medium 1pt 1pt none solid solid 0 black black;padding:0 5.4pt;" valign="top">
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:12.05pt;"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN"> </span></p>
<table class="MsoNormalTable" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height:10.5pt;">
<td style="border:medium none;height:10.5pt;padding:0 5.4pt;" valign="top">
<p class="MsoNormal" style="margin-bottom:.0001pt;"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN">&lt;T&gt; T merge(T entity)</span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;">
</td>
<td style="width:128.05pt;padding:0 5.4pt;" width="171" valign="top">
<p class="Pa45"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN"> </span></p>
<table class="MsoNormalTable" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height:46.95pt;">
<td style="border:medium none;height:46.95pt;padding:0 5.4pt;" valign="top">
<p class="Pa35"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN">Updates the data in the database with the values contained in the JPA entity&#8217;s properties.</span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;">
</td>
<td style="width:114.25pt;padding:0 5.4pt;" width="152" valign="top">
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:12.05pt;"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN"> </span></p>
<table class="MsoNormalTable" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height:10.5pt;">
<td style="border:medium none;height:10.5pt;padding:0 5.4pt;" valign="top">
<p class="MsoNormal" style="margin-bottom:.0001pt;"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN">em.merge(customer);</span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;">
</td>
</tr>
<tr>
<td style="width:129.4pt;padding:0 5.4pt;" width="173" valign="top">
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:12.05pt;"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN"> </span></p>
<table class="MsoNormalTable" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height:10.5pt;">
<td style="border:medium none;height:10.5pt;padding:0 5.4pt;" valign="top">
<p class="MsoNormal" style="margin-bottom:.0001pt;"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN">remove(Object entity) </span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;">
</td>
<td style="width:128.05pt;padding:0 5.4pt;" width="171" valign="top">
<p class="Pa45"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN"> </span></p>
<table class="MsoNormalTable" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height:46.95pt;">
<td style="border:medium none;height:46.95pt;padding:0 5.4pt;" valign="top">
<p class="Pa35"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN">Deletes the row corresponding to the JPA entity from the database table the entity maps to.</span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;">
</td>
<td style="width:114.25pt;padding:0 5.4pt;" width="152" valign="top">
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:12.05pt;"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN"> </span></p>
<table class="MsoNormalTable" style="border:medium none;border-collapse:collapse;" border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr style="height:10.5pt;">
<td style="border:medium none;height:10.5pt;padding:0 5.4pt;" valign="top">
<p class="MsoNormal" style="margin-bottom:.0001pt;"><span style="font-size:10pt;font-family:&quot;color:black;" lang="EN-IN">em.remove(customer);</span></p>
</td>
</tr>
</tbody>
</table>
<p class="MsoNormal" style="margin-bottom:.0001pt;line-height:normal;">
</td>
</tr>
</tbody>
</table>
</div>
<p>Just like the <em>persist()</em> method, the methods listed on the above table must be invoked inside a transaction, therefore a DAO&#8217;s method invoking the above EntityManger methods should follow the pattern in our DAO&#8217;s <em>persist()</em> method (lookup EntityManager, begin a transaction, invoke the method, commit the transaction, look for any exceptions and throw a RuntimeException to roll back the transaction, if necessary).</p>
<p>If we are working with a JSF application, such as in our example, we would need to write additional methods on our Controller managed bean that would invoke DAO methods whenever a user submits a form. Additionally we would have to write additional JSP pages to create the user interface.</p>
<p>As we will see later in this article, NetBeans can automate most of the steps described in the previous two paragraphs. But before we get there, we will discuss one great feature of NetBeans: automated generation of JPA entities from an existing database schema.</p>
<h1>Automated Generation of JPA Entities</h1>
<p>In the previous section, we saw how we can automatically create database tables from JPA entities. This is an optional feature of the JPA specification, however most JPA implementations implement it. One feature that is not available from JPA is the converse, generating JPA entities from database tables. Luckily for us, NetBeans provides this functionality.</p>
<p>In this section, we will be using a custom database schema. In order to create the schema, we need to execute an SQL script that will create the schema and populate some of its tables. To do this, we need to go to the Services window, right-click on <strong>JavaDB</strong>, then select <strong>Create Database&#8230;</strong>.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%2016.png" alt="" /></p>
<p>We then need to add the database information in the <strong>Create Java DB Database</strong> wizard.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%2017.png" alt="" /></p>
<p>At this point, we can open the SQL script by going to <strong>File | Open File&#8230;</strong>, then navigating to its location on our disk and opening it.</p>
<p style="margin-left:40px;margin-right:40px;"><em>The file name of our script is create_populate_tables.sql.</em></p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%2018.png" alt="" /></p>
<p>Once we have opened the SQL script, we need to select our newly created connection from the <strong>Connection</strong> combo box, then click on the <img src="http://www.packtpub.com/files/images/javaee-article-image%2019.png" alt="" /> icon to execute it. Our database will now have a number of tables.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%2020.png" alt="" /></p>
<p>NetBeans allows us to generate JPA entities from an existing schema. To do so we need to create a new project, then right-click on the project, then select <strong>New | Entity Classes from Database&#8230;</strong>.</p>
<p style="margin-left:40px;margin-right:40px;"><em>NetBeans allows us to generate JPA entities from pretty much any kind of Java project. In our example we will be using a Web Application project.</em></p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%2021.png" alt="" /></p>
<p>We see a <strong>New Entity Classes from Database</strong> dialog as depicted here:</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%2022.png" alt="" /></p>
<p>At this point we can either select an existing data source, or, like we did in the previous example, create one &#8220;on the fly&#8221;. In our example we created a new one, then selected the database connection we created earlier in this section.</p>
<p>Once we have created or selected our data source, we need to select one or more tables to use to generate our JPA entities. If we wish to create JPA entities for all tables, we can simply click on the <strong>Add All&gt;&gt;</strong> button.</p>
<p>After clicking <strong>Next</strong>, NetBeans gives us the opportunity to change the names of the generated classes, although the defaults tend to be sensible. We should also specify a package for our classes, and it is a good idea to check the <strong>Generate Named Query Annotations for Persistent Fields</strong> checkbox.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%2023.png" alt="" /></p>
<p>In the next screen in the wizard, we can select how associated entities will be fetched (eagerly or lazily). By default, the default behavior is selected, which is to fetch &#8220;one-to-one&#8221; and &#8220;many-to-one&#8221; relationships eagerly, and &#8220;one-to-many&#8221; and &#8220;many-to-many&#8221; relationships lazily.</p>
<p>Additionally, we can select what collection type to use for the &#8220;many&#8221; side of a &#8220;one-to-many&#8221; or &#8220;many-to-many&#8221; relationship. The default value is <em>java.util.Collection</em>. Other valid values are <em>java.util.List</em> and <em>java.util.Set</em>.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%2024.png" alt="" /></p>
<p>Checking the <strong>Fully Qualified Database Table Names</strong> checkbox results in adding the catalog and schema elements of the table being mapped to the @Table annotation for each generated entity.</p>
<p>Checking the <strong>Attributes for Regenerating Tables</strong> results in the generated @Column annotations having attributes such as length, which specifies the maximum length allowed in the column; nullable, which specifies if null values are allowed in the column; precision and scale, which specify the precision and scale of decimal values, respectively. Checking this attribute also adds the uniqueConstraints attribute to the generated @Table annotation to specify any unique constraints that apply to the table, if necessary. When clicking <strong>Finish</strong>, NetBeans generates JPA entities for all tables in the database. Our database contained a table named CUSTOMER table. Let&#8217;s take a look at the generated Customer JPA entity.</p>
<pre style="margin-left:40px;">package com.ensode.jpa;
//Import statements removed for brevity.
@Entity
@Table(name = "CUSTOMER")
@NamedQueries({@NamedQuery(name = "Customer.findByCustomerId",
query = "SELECT c FROM Customer c WHERE c.customerId = :customerId"),@NamedQuery
(name = "Customer.findByFirstName",
query = "SELECT c FROM Customer c WHERE c.firstName = :firstName"),
@NamedQuery(name = "Customer.findByMiddleName",
query = "SELECT c FROM Customer c WHERE c.middleName = :middleName"),
@NamedQuery(name = "Customer.findByLastName",
query = "SELECT c FROM Customer c WHERE c.lastName = :lastName"),
@NamedQuery(name = "Customer.findByEmail",
query = "SELECT c FROM Customer c WHERE c.email = :email")})
public class Customer implements Serializable {
@Id
@Column(name = "CUSTOMER_ID", nullable = false)
private Integer customerId;
@Column(name = "FIRST_NAME")
private String firstName;
@Column(name = "MIDDLE_NAME")
private String middleName;
@Column(name = "LAST_NAME")
private String lastName;
@Column(name = "EMAIL")
private String email;
@OneToMany(mappedBy = "customerId")
private Collection&lt;CustomerOrder&gt; customerOrderCollection;
@OneToMany(mappedBy = "customerId")
private Collection&lt;Address&gt; addressCollection;
@OneToMany(mappedBy = "customerId")
private Collection&lt;Telephone&gt; telephoneCollection;
//Getters, setters and other generated methods and
//constructors removed for brevity.
}</pre>
<p>As we can see, NetBeans generates a class decorated with the @Entity annotation, which marks the class as a JPA entity. Notice that NetBeans automatically decorated one of the fields with the @Id annotation, based on the primary key constraint in the table used to generate the JPA entity. Notice that no primary key generation strategy is used. We either need to populate the primary key ourselves, or add the @GeneratedValue annotation manually.</p>
<p>Also notice the @Table annotation. This is an optional annotation that indicates what table our JPA entity maps to. If the @Table annotation is not used, then our entity will map to a table having the same name as the entity class (case insensitive). In our particular example, the @Table annotation is redundant, but there are cases where it is useful. For example, some database schemas have tables named in plural (CUSTOMERS), but it makes sense to name our entities in singular (Customer). Additionally, the standard naming convention for database tables containing more than one word is to use underscores to separate words (CUSTOMER_ORDER) where in Java the standard is to use camel case (CustomerOrder). The @Table annotation allows us to follow established naming standards in both the relational database and the Java worlds.</p>
<h2>Named Queries and JPQL</h2>
<p>Next, we see the @NamedQueries annotation (this annotation is only generated if we click on the <strong>Generate Named Query Annotations for Persistent Fields</strong> checkbox of the <strong>New Entity Classes from Database</strong> wizard). This query contains a value attribute (the attribute name can be omitted from the code since it is the only attribute in this annotation). The value of this attribute is an array of @NamedQuery annotations. The @NamedQuery annotation has a name attribute, which is used to give it a logical name (By convention, the JPA entity name is used as part of the query name. As we can see in the generated code, the <strong>New Entity Classes from Database</strong> wizard follows this convention), and a query attribute, which is used to define a <strong>Java Persistence Query Language (JPQL)</strong> query to be executed by the named query.</p>
<p>JPQL is a JPA-specific query language. Its syntax is similar to SQL. The <strong>New Entity Classes from Database</strong> wizard generates a JPQL query for each field in our entity. When the query is executed, a List containing all instances of our entity that match the criteria in the query will be returned. The following code snippet illustrates this process.</p>
<pre style="margin-left:40px;">import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
public class CustomerDAO {
public List findCustomerByLastName(String someLastName)
{
//code to lookup EntityManager omitted for brevity
Query query =
em.createNamedQuery("Customer.findByLastName");
query.setParameter("lastName", someLastName);
List resultList = query.getResultList();
return resultList;
}
}</pre>
<p>Here we see a DAO object containing a method that will return a list of Customer entities for customers whose last name equals the one provided in the method&#8217;s parameter. In order to implement this, we need to obtain an instance of an object of type <em>javax.pesistence.Query</em>. As we can see in the previous code snippet, this can be accomplished by invoking the <em>createNamedQuery()</em> method in EntityManager, passing the query name (as defined in the @NamedQuery annotation) as a parameter. Notice that the named queries generated by the NetBeans wizard contain strings preceded by a colon (:), these strings are <strong>named parameters</strong>. Named parameters are &#8220;placeholders&#8221; we can use to substitute for appropriate values.</p>
<p>In our example, we set the <em>lastName</em> named parameter in JPQL query with the <em>someLastName</em> argument passed to our method.</p>
<p>Once we have populated all parameters in our query, we can obtain a List of all matching entities by invoking the <em>getResultList()</em> method in our Query object.</p>
<p>Going back to our generated JPA entity, notice the wizard automatically placed the @Id annotation in the field mapping to the table&#8217;s primary key. Additionally, each field is decorated with the @Column annotation, which allows us to follow standard naming conventions in both the relational database and Java worlds. In addition to allowing us to specify what column each field maps to, the @Column annotation has a nullable attribute that allows us to specify if the column accepts null values or not. As we can see, the wizard automatically sets nullable to false for the entity&#8217;s primary key field.</p>
<h2>Entity Relationships</h2>
<p>There are several annotations we can use in JPA entities to define relationships between them. In our Customer entity shown above, we can see that the wizard detected several one-to-many relationships in the CUSTOMER table, and automatically added the @OneToMany annotation to define these relationships in our entity. Notice that each field annotated with the @OneToMany annotation is of type <em>java.util.Collection</em>. The Customer is the &#8220;one&#8221; side of the relationship, since a customer can have many orders, many addresses (street, mail), or many telephone numbers (home, work, cell). Notice that the wizard uses generics to specify the type of objects we can add to each collection. Objects in these collections are the JPA entities mapping to the corresponding tables in our database schema.</p>
<p>Notice that @OneToMany annotation has a <em>mappedBy</em> attribute. This attribute is necessary since each of these relationships is bi-directional (we can access all addresses for a customer, and for a given address, we can obtain what customer it belongs to). The value of this attribute must match the name of the field on the other side of the relationship. Let&#8217;s take a look at the Address entity to illustrate the other side of the customer-address relationship.</p>
<pre style="margin-left:40px;">package com.ensode.jpa;
//imports omitted for brevity.
@Entity
@Table(name = "ADDRESS")
//Named queries omitted for brevity
public class Address implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "ADDRESS_ID", nullable = false)
private Integer addressId;
@Column(name = "ADDR_LINE_1")
private String addrLine1;
@Column(name = "ADDR_LINE_2")
private String addrLine2;
@Column(name = "CITY")
private String city;
@Column(name = "ZIP")
private String zip;
@JoinColumn(name = "ADDRESS_TYPE_ID", referencedColumnName = "ADDRESS_TYPE_ID")
@ManyToOne
private AddressType addressTypeId;
@JoinColumn(name = "CUSTOMER_ID", referencedColumnName = "CUSTOMER_ID")
@ManyToOne
private Customer customerId;
@JoinColumn(name = "US_STATE_ID", referencedColumnName = "US_STATE_ID")
@ManyToOne
private UsState usStateId;
// Getters, setters, constructor and other methods
// omitted for brevity.
}</pre>
<p>Notice that the Address entity has a <em>customerId</em> field. This field is of type Customer, the entity we were just discussing.</p>
<p style="margin-left:40px;margin-right:40px;"><em>A more appropriate name for this field would have been customer, the <strong>New Entity Classes from Database</strong> names the field based on the column name in the database. This is one small disadvantage of using the wizard to generate JPA entities. Of course we are free to rename the field and the corresponding getter and setter methods. Additionally, we would have to change the value of the mappedBy attribute of the @OneToMany annotation on the other side of the relationship.</em></p>
<p>Notice that the field is decorated with a @ManyToOne annotation. This annotation marks the &#8220;many&#8221; side of the one-to-many relationship between Customer and Address. Notice that the field is also decorated with the @JoinColumn annotation. The name attribute of this annotation indicates the column in the database our entity maps to that defines the foreign key constraint between the ADDRESS and CUSTOMER tables. The referencedColumnName attribute of @JoinColumn is use to indicate the primary key column of the table on the &#8220;one&#8221; side of the relationship (CUSTOMER, in our case).</p>
<p>In addition to one-to-many and many-to-one relationships, JPA provides annotations to denote many-to-many, and one-to-one relationships. In our schema, we have many-to-many relationships between the CUSTOMER_ORDER and ITEM tables, since an order can have many items, and an item can belong to many orders.</p>
<p style="margin-left:40px;margin-right:40px;"><em>The table to hold orders was named CUSTOMER_ORDER since the word ORDER is a reserved word in SQL.</em></p>
<p>Let&#8217;s take a look at the <em>CustomerOrder</em> JPA entity to see how the many-to-many relationship is defined.</p>
<pre style="margin-left:40px;">package com.ensode.jpa;
//imports deleted for brevity
@Entity
@Table(name = "CUSTOMER_ORDER")
//Named queries deleted for brevity
public class CustomerOrder implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "CUSTOMER_ORDER_ID", nullable = false)
private Integer customerOrderId;
@Column(name = "ORDER_NUMBER")
private String orderNumber;
@Column(name = "ORDER_DESCRIPTION")
private String orderDescription;
@JoinTable(name = "ORDER_ITEM", joinColumns =
{@JoinColumn(name = "CUSTOMER_ORDER_ID",
referencedColumnName =
"CUSTOMER_ORDER_ID")},
inverseJoinColumns = {@JoinColumn(name = "ITEM_ID",
referencedColumnName = "ITEM_ID")})
@ManyToMany
private Collection&lt;Item&gt; itemIdCollection;
@JoinColumn(name = "CUSTOMER_ID", referencedColumnName = "CUSTOMER_ID")
@ManyToOne
private Customer customerId;
//Constructor, getters, setters and other methods deleted for
//brevity
}</pre>
<p>Notice that the <em>CustomerOrder</em> entity has a property of type <em>java.util.Collection</em> named <em>itemIdCollection</em>.</p>
<p style="margin-left:40px;margin-right:40px;"><em>Again, the property name generated by the wizard could be improved. A better name would have been itemCollection.</em></p>
<p>This property holds all items for the order. Notice that the field is decorated with the @ManyToMany annotation. This annotation is used to declare a many-to-many relationship between the <em>CustomerOrder</em> and Item JPA entities. Notice that the field is also annotated with the @JoinTable annotation. This annotation is necessary since a join table is necessary in a database schema whenever there is a many-to-many relationship between tables. Using a join table allows us to keep the data in the database normalized.</p>
<p>The @JoinTable annotation allows us to specify the table in the schema that is used to denote the many-to-many relationship in the schema. The value of the name attribute of @JoinTable must match the name of the join table in the schema. The value of the joinColumns attribute of @JoinColumn must be the foreign key relationship between the join table and the owning side of the relationship. We already looked at the @JoinColumn annotation when looking at one-to-many relationships. In this case, its name attribute must match the name of the column in the join table that has the foreign key relationship, and its referencedColumnName attribute must indicate the name of the primary key column on the owning side of the relationship. The value of the inverseJoinColumns attribute of @JoinTable has a similar role as its joinColumns attribute, except it indicates the corresponding columns for the non-owning side of the relationship.</p>
<p>The side of the many-to-many relationship containing the above annotations is said to be the owning side of the relationship, let&#8217;s look at how the many-to-many relationship is defined in the non-owning side of the relationship, which, in our case is the <em>Item</em> JPA entity.</p>
<pre style="margin-left:40px;">package com.ensode.jpa;
//Imports deleted for brevity
@Entity
@Table(name = "ITEM")
//Named queries deleted for brevity
public class Item implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "ITEM_ID", nullable = false)
private Integer itemId;
@Column(name = "ITEM_NUMBER")
private String itemNumber;
@Column(name = "ITEM_SHORT_DESC")
private String itemShortDesc;
@Column(name = "ITEM_LONG_DESC")
private String itemLongDesc;
@ManyToMany(mappedBy = "itemIdCollection")
private Collection&lt;CustomerOrder&gt; customerOrderIdCollection;
//Constructors, getters, setters and other methods
//deleted for brevity.
}</pre>
<p>As we can see, the only thing we need to do on this side of the relationship is to create a <em>Collection</em> property, decorate it with the @ManyToMany annotation and specify the property name in the other side of the relationship as the value of its <em>mappedBy</em> attribute.</p>
<p>In addition to one-to-many and many-to-many relationships, it is possible to create one-to-one relationships between JPA entities.</p>
<p>The annotation to use to indicate a one-to-one relationship between two JPA entities is @OneToOne. Our schema doesn&#8217;t have any one-to-one relationship between tables, therefore this annotation was not added to any of the entities generated by the wizard.</p>
<p style="margin-left:40px;margin-right:40px;"><em>One-to-one relationships are not very popular in database schemas, since all data in a single entity is kept in a single table. Nevertheless JPA supports one-to-one relationships in case it is needed.</em></p>
<p>The procedure to indicate a one-to-one relationship between two entities is similar to what we have already seen, the owning side of the relationship must have a field of the type of the JPA entity at the other side of the relationship. This field must be decorated with the @OneToOne and @JoinColumn annotations.</p>
<p>Suppose we had a schema in which a one-to-one relationship was defined between two tables named PERSON and BELLY_BUTTON. This is a one-to-one relationship since each person has one belly button and each belly button belongs to only one person. (The reason the schema was modeled this way instead of having the columns relating to the BELLY_BUTTON table in the PERSON table escapes me, but bear with me, I&#8217;m having a hard time coming up with a good example!).</p>
<pre style="margin-left:40px;">@Entity
public class Person implements Serializable {
@JoinColumn(name="BELLY_BUTTON_ID")
@OneToOne
private BellyButton bellyButton;
public BellyButton getBellyButton(){
return bellyButton;
}
public void setBellyButton(BellyButton bellyButton){
this.bellyButton = bellyButton;
}
}</pre>
<p>If the one-to-one relationship is <strong>unidirectional</strong> (we can only get the belly button from the person), this would be all we had to do. If the relationship is <strong>bidirectional</strong>, then we need to add the @OneToOne annotation on the other side of the relationship, and use its mappedBy attribute to indicate the other side of the relationship.</p>
<pre style="margin-left:40px;">@Entity
@Table(name="BELLY_BUTTON")
public class BellyButton implements Serializable(
{
@OneToOne(mappedBy="bellyButton")
private Person person;
public Person getPerson(){
return person;
}
public void getPerson(Person person){
this.person=person;
}
}</pre>
<p>As we can see, the procedure to establish one-to-one relationships is very similar to the procedure used to establish one-to-many and many-to-many relationships.</p>
<p>Once we have generated JPA entities from a database, we need to write additional code containing business and presentation logic. Alternatively, we can use NetBeans to generate code for these two layers.</p>
<h1>Generating JSF Applications from JPA Entities</h1>
<p>One very nice feature of NetBeans is that it allows us to generate JSF applications that will perform create, read, update, and delete (CRUD) operations from existing JPA entities. This feature, combined with the ability to create JPA entities from an existing database schema, as described in the previous section, allows us to write web applications that interact with a database in record time.</p>
<p>To generate JSF pages from existing JPA entities, we need to right-click on the project and select <strong>New | JSF Pages from Entity Classes&#8230;</strong>.</p>
<p style="margin-left:40px;margin-right:40px;"><em>In order for us generate JSF pages from existing JPA entities, the current project must be a Web application project.</em></p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%2025.png" alt="" /></p>
<p>At this point we are presented with the <strong>New JSF Pages from Entity Classes</strong> wizard</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%2026.png" alt="" /></p>
<p>We need to select one or more JPA entities. We would typically want to select all of them. They can easily be selected by clicking on the <strong>Add All&gt;&gt;</strong> button.</p>
<p>The next page in the wizard allows us to specify a package for newly created JSF managed beans. Two types of classes are generated by the wizard: <strong>JPA Controllers</strong> and <strong>JSF Classes</strong>. We can specify packages for both of these individually.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%2027.png" alt="" /></p>
<p>We are also given the opportunity to specify a folder for the JSF pages to be created. If we leave this field blank, pages will be created in our project&#8217;s <strong>Web Pages</strong> folder.</p>
<p style="margin-left:40px;margin-right:40px;"><em>The value of the <strong>JPA Controller Package</strong> and <strong>JSF Classes Package</strong> text fields default to the package where our JPA entities reside. It is a good idea to modify this default, since placing the JSF managed beans in a different package separates the data access layer classes from the user interface and controller layers of our application.</em></p>
<p>At this point in the wizard we can specify if we would like the generated pages to be Ajax enabled. This can be done by simply checking the Ajax-enable generated pages checkbox.</p>
<p>After clicking <strong>Finish</strong>, a complete web application that can perform CRUD operations will be created.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%2028.png" alt="" /></p>
<p>As we can see, NetBeans generates a folder for each of our entities under the <strong>Web Pages</strong> folder of our application. Each of the folders has a <strong>Detail, Edit, List,</strong> and <strong>New</strong> JSP files. The <strong>Detail</strong> JSP will display all properties for a JPA entity, the <strong>Edit</strong> JSP will allow users to update information for a specific entity, the <strong>List</strong> JSP will display all instances of a specific entity in the database, and the <strong>New</strong> JSP will provide functionality to create new entities.</p>
<p>The generated application is a standard JSF application; we can execute it by simply right-clicking on the project and selecting <strong>Run</strong>. At that point the usual things happen: the application server is started if it wasn&#8217;t already up, the application is deployed and a web browser window is opened displaying the welcome page for our application.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%2029.png" alt="" /></p>
<p>As we can see, the welcome page contains a link corresponding to each of our JPA entities. The links will display a table displaying all existing instances of our entity in the database. Then we click on the <strong>Show All Customer Items</strong>.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%2030.png" alt="" /></p>
<p>Since we haven&#8217;t inserted any data to the database yet, the page displays the message (<strong>No Customer Items Found</strong>). We can insert a customer into the database by clicking on the <strong>New Customer</strong> link.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%2031.png" alt="" /></p>
<p>Notice how an input field is generated for each property in our entity, which in turn corresponds to each column in the database table.</p>
<p style="margin-left:40px;margin-right:40px;"><em>As we can see, an input field was generated for the primary key field of our entity. This field is only generated if the JPA entity does not use a primary key generation strategy.</em></p>
<p>For properties in which there is a one-to-many relationship, a multiple select box is generated (in our example they are empty, since we haven&#8217;t added any to the database yet).</p>
<p>After entering some information on the page and clicking on the <strong>Create</strong> link, a new customer is inserted into the database and we are directed to the <strong>List</strong> JSP.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%2032.png" alt="" /></p>
<p>At this point we can see our newly created customer in the list of customers on this JSP. Notice that the JSP has links to <strong>Show</strong>, <strong>Edit</strong>, and <strong>Destroy</strong> (delete) the entity.</p>
<p>Let&#8217;s say we would want to add an address for our customer. We could do so by clicking on the <strong>Index</strong> link, then clicking on <strong>Show All Address Items</strong>, then on <strong>New Address</strong>.</p>
<p style="text-align:center;"><img src="http://www.packtpub.com/files/images/javaee-article-image%2033.png" alt="" /></p>
<p>The Address entity is at the &#8220;one&#8221; end of several one-to-many relationships, notice how a combo box is generated for each one of the entities at the &#8220;many&#8221; end. Since we wish to assign this address to the customer we just added, we attempt to select a customer from the <strong>CustomerId</strong> combo box.</p>
<p style="margin-left:40px;margin-right:40px;"><em>A better name could be used for the CustomerId field. The reason this is the label for the combo box is because it matches the property name on the Address JPA entity, which in turn could have a better name, such as customer. Recall that all entities on this project were automatically generated from an existing database schema.</em></p>
<p>Clicking on the combo box reveals a cryptic, almost undecipherable (from the users point of view anyway), label for our customer. The reason we see this label is because the labels generated for each item in the combo box come from the <em>toString()</em> method of the entities used to populate it. We can work around this issue by modifying the <em>toString()</em> method so that it returns a user-friendly String suitable to use as a label.</p>
<p>As we can see, the generated code from NetBeans wizards could certainly use some tweaking, such as modifying the <em>toString()</em> methods of each JPA entity so that it can be used as a label, modifying some of the property names on the entities so that they make more sense to us developers, modifying the labels on the generated JSF pages so that they are more user friendly. Nevertheless, as we can see we can have a fully working application completely created by a few clicks of the mouse. This functionality certainly saves us a lot of time and effort (just don&#8217;t tell your boss about it).</p>
<h1>Summary</h1>
<p>In this article, we saw the many ways in which NetBeans can help us speed up development of applications taking advantage of the Java Persistence API (JPA).</p>
<p>We saw how NetBeans can generate new JPA classes with all required annotations already in place.</p>
<p>Additionally, we covered how NetBeans can automatically generate code to persist a JPA entity to a database table.</p>
<p>We also covered how NetBeans can generate JPA entities from an existing database schema, including the automated generation of JPQL named queries.</p>
<div class="header"><strong>Java EE 5 Development with NetBeans 6</strong></div>
<div class="header"><strong><br />
</strong></div>
<table border="0" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<td width="99" valign="top"><a href="http://www.packtpub.com/java-ee5-development-with-netbeans-6/book"><img class="left" title="Java EE 5 Development with NetBeans 6" src="http://images.packtpub.com/images/100x123/1847195466.png" border="0" alt="Java EE 5 Development with NetBeans 6" width="99" height="123" /></a></td>
<td valign="top">
<ul>
<li>Develop professional enterprise Java EE applications quickly and easily with this popular IDE</li>
</ul>
<ul>
<li>Use features of the popular NetBeans IDE to improve Java EE development</li>
<li>Careful instructions and screenshots lead you through the options available</li>
<li>Covers the major Java EE APIs such as JSF, EJB 3 and JPA, and how to work with them in NetBeans</li>
<li>Covers the NetBeans Visual Web designer in detail</li>
</ul>
<ul>
<li><a href="http://www.packtpub.com/java-ee5-development-with-netbeans-6/book">http://www.packtpub.com/java-ee5-development-with-netbeans-6/book</a></li>
</ul>
</td>
</tr>
</tbody>
</table>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/javadude.wordpress.com/534/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/javadude.wordpress.com/534/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/javadude.wordpress.com/534/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/javadude.wordpress.com/534/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/javadude.wordpress.com/534/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/javadude.wordpress.com/534/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/javadude.wordpress.com/534/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/javadude.wordpress.com/534/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/javadude.wordpress.com/534/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/javadude.wordpress.com/534/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javadude.wordpress.com&blog=3891833&post=534&subd=javadude&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://javadude.wordpress.com/2009/04/25/interacting-with-databases-through-the-java-persistence-api/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c590146f757718a268c168a7eee0f53f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">devdude</media:title>
		</media:content>

		<media:content url="http://images.packtpub.com/images/100x123/1847195466.png" medium="image">
			<media:title type="html">Java EE 5 Development with NetBeans 6</media:title>
		</media:content>

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%201.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%202.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%203.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%204.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%205.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%206.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%207.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%208.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%209.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2010.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2011.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2012.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2013.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2014.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2015.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2016.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2017.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2018.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2019.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2020.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2021.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2022.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2023.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2024.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2025.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2026.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2027.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2028.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2029.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2030.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2031.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2032.png" medium="image" />

		<media:content url="http://www.packtpub.com/files/images/javaee-article-image%2033.png" medium="image" />

		<media:content url="http://images.packtpub.com/images/100x123/1847195466.png" medium="image">
			<media:title type="html">Java EE 5 Development with NetBeans 6</media:title>
		</media:content>
	</item>
		<item>
		<title>Tutorial: Reading from the DB with Netbeans and ZK (Part 2)</title>
		<link>http://javadude.wordpress.com/2009/03/24/tutorial-reading-from-the-db-with-netbeans-and-zk-part-2/</link>
		<comments>http://javadude.wordpress.com/2009/03/24/tutorial-reading-from-the-db-with-netbeans-and-zk-part-2/#comments</comments>
		<pubDate>Tue, 24 Mar 2009 10:07:30 +0000</pubDate>
		<dc:creator>devdude</dc:creator>
				<category><![CDATA[tutorial]]></category>
		<category><![CDATA[jpa]]></category>
		<category><![CDATA[netbeans]]></category>
		<category><![CDATA[zk]]></category>

		<guid isPermaLink="false">http://javadude.wordpress.com/?p=510</guid>
		<description><![CDATA[In this part 2 we modify the ZK project from part 1 and add data binding and a detail view.
Before we start adding the new functions, you might want to look in some of the project settings that are default when you create a new ZK360 type web project. Both context path (under Project properties&#124;Run), [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javadude.wordpress.com&blog=3891833&post=510&subd=javadude&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p style="text-align:justify;">In this part 2 we modify the ZK project from part 1 and add data binding and a detail view.</p>
<p style="text-align:justify;">Before we start adding the new functions, you might want to look in some of the project settings that are default when you create a new ZK360 type web project. Both <em>context path</em> (under Project properties|Run), as well the <em>Display Name</em> in the web.xml (under project explorer|configuration files) . You better change the default to avoid confusion when starting to create the second project.</p>
<p style="text-align:justify;">I recommend to have a look at these 2 documents: <strong><em>ZK Developers Guide</em></strong> and the <em><strong>ZK Reference Doc</strong></em> (<a href="http://docs.zkoss.org/wiki/Documentation" target="_blank">link</a>), giving you more insights how ZK works and how feature rich it is. I noticed the available Netbeans palette does not show all available features, so you are better of browsing the docs and look at the sourcecode of the ZK Explorer application (<a href="http://www.zkoss.org/zkdemo/userguide" target="_blank">Live Demo</a>).</p>
<p style="text-align:justify;">Back to part 2.</p>
<p style="text-align:justify;"><em>Requirements:</em></p>
<ul style="text-align:justify;">
<li>Netbeans 6.5 with a running derby DB and the sample database (customer table)</li>
<li>Installed ZK 3.6.0 plugin</li>
<li>The project from part 1 (<a href="http://javadude.wordpress.com/2009/03/21/tutorial-reading-from-the-db-with-netbeans-and-zk/" target="_blank">link</a>)</li>
</ul>
<p style="text-align:justify;"><em>Content</em></p>
<p style="text-align:justify;">1. Open the ZKReadDB project from part 1<br />
2. Change the controller class<br />
3. Activate the Data Binding Manager<br />
4. Make the listbox work witha model and refer the listitems to the fields<br />
5. Implement the detail view<br />
6. Add the detail view with textboxes<br />
7. The complete index.zul and controller.java</p>
<p style="text-align:justify;"><span id="more-510"></span><strong>1. Open the ZKReadDB project from part 1</strong></p>
<p style="text-align:justify;">We dont need to change the underlying data class (Customer.java) but need to make adjustments to the controller class (Controller.java) and our zul file (index.zul)</p>
<p style="text-align:justify;"><strong>2. Change the controller class</strong></p>
<p style="text-align:justify;">The changes are required to implement the detail view for the selected customer record in the listbox. We add 1 customer instance plus getter/setter.</p>
<p style="text-align:justify;">
<pre class="brush: java;">
[..]
    Customer selected = new Customer();
[..]
    public Customer getSelected() {
        return selected;
    }

    public void setSelected(Customer selected) {
        this.selected = selected;
    }
[..]   
</pre>
<p style="text-align:justify;"><strong>3. Activate the Data Binding Manager</strong></p>
<p style="text-align:justify;">Add at the top of index.zul</p>
<p style="text-align:justify;">
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;?init class=&quot;org.zkoss.zkplus.databind.AnnotateDataBinderInit&quot; ?&gt;
[..]   
</pre>
<p style="text-align:justify;"><strong>4. Make the listbox work with a model and refer the listitems to the fields</strong></p>
<p style="text-align:justify;">
<pre class="brush: xml;">
	&lt;listbox id=&quot;lb&quot; model=&quot;@{win.customers}&quot;
[..]
        &lt;listitem self=&quot;@{each=customers}&quot;&gt;
	&lt;listcell label=&quot;@{customers.name}&quot;/&gt;
	&lt;listcell label=&quot;@{customers.email}&quot;/&gt;
        &lt;/listitem&gt;
[..]   
</pre>
<p style="text-align:justify;"><strong>5. Implement the detail view</strong></p>
<p style="text-align:justify;">Use the <em>selected item</em> method of the listbox</p>
<p style="text-align:justify;">
<pre class="brush: xml;">
[..]
	&lt;listbox id=&quot;lb&quot; .. selectedItem=&quot;@{win.selected}&quot; ..&gt;
[..]   
</pre>
<p style="text-align:justify;"><strong>6. Add the detail view with textboxes</strong></p>
<p style="text-align:justify;">Add a separate groupbox with hbox and vbox to create a detail view. You can add more fields of the customer table if you like to following the name and email sample.</p>
<p style="text-align:justify;">
<pre class="brush: xml;">
[..]
        &lt;groupbox id=&quot;gb&quot; mold=&quot;3d&quot; width=&quot;600px&quot;&gt;
            &lt;caption label=&quot;Selected Customer&quot;/&gt;
            Name: &lt;textbox id=&quot;name&quot;  cols=&quot;50&quot; value=&quot;@{win.selected.name}&quot; /&gt;
            Email: &lt;textbox id=&quot;email&quot; value=&quot;@{win.selected.email}&quot; /&gt;
        &lt;/groupbox&gt;
[..]   
</pre>
<p style="text-align:justify;"><strong>7. The complete index.zul and controller.java</strong></p>
<p style="text-align:justify;">
<pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;?init class=&quot;org.zkoss.zkplus.databind.AnnotateDataBinderInit&quot; ?&gt;
&lt;?page title=&quot;My Page Title&quot;?&gt;
&lt;window id=&quot;win&quot; use=&quot;data.Controller&quot; border=&quot;normal&quot; width=&quot;75%&quot;&gt;
    Customer DB
	&lt;listbox id=&quot;lb&quot; model=&quot;@{win.customers}&quot; selectedItem=&quot;@{win.selected}&quot; mold=&quot;paging&quot; pageSize=&quot;4&quot;&gt;
	&lt;listhead sizable=&quot;true&quot;&gt;
	&lt;listheader label=&quot;name&quot; width=&quot;50px&quot;/&gt;
	&lt;listheader label=&quot;email&quot; width=&quot;250px&quot;/&gt;
        &lt;/listhead&gt;
	&lt;listitem self=&quot;@{each=customers}&quot;&gt;
	&lt;listcell label=&quot;@{customers.name}&quot;/&gt;
	&lt;listcell label=&quot;@{customers.email}&quot;/&gt;
        &lt;/listitem&gt;
    &lt;/listbox&gt;
  &lt;separator bar=&quot;true&quot;/&gt;
    &lt;hbox&gt;
        &lt;groupbox id=&quot;gb&quot; mold=&quot;3d&quot; width=&quot;600px&quot;&gt;
            &lt;caption label=&quot;Selected Customer&quot;/&gt;
            Name: &lt;textbox id=&quot;name&quot;  cols=&quot;50&quot; value=&quot;@{win.selected.name}&quot; /&gt;
            Email: &lt;textbox id=&quot;email&quot; value=&quot;@{win.selected.email}&quot; /&gt;
        &lt;/groupbox&gt;
    &lt;/hbox&gt;
&lt;/window&gt;
</pre>
<p style="text-align:justify;">
<pre class="brush: java;">
package data;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.zkoss.zul.Window;

public class Controller extends Window {

    List customers = new ArrayList();
    Customer selected = new Customer();

    public Controller() {
        EntityManagerFactory emf;
        emf = Persistence.createEntityManagerFactory(&quot;ZKReadDBPU&quot;);
        EntityManager em = emf.createEntityManager();
        javax.persistence.Query q = em.createQuery(&quot;select c from Customer as c&quot;);
        customers = q.getResultList();
        em.close();
    }

    public List getCustomers() {
        return customers;
    }

    public Customer getSelected() {
        return selected;
    }

    public void setSelected(Customer selected) {
        this.selected = selected;
    }
}
</pre>
<p style="text-align:justify;"><strong>Result</strong></p>
<p style="text-align:justify;">
<div id="attachment_517" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.files.wordpress.com/2009/03/bv2009032417590033.jpg"><img class="size-medium wp-image-517" title="bv2009032417590033" src="http://javadude.files.wordpress.com/2009/03/bv2009032417590033.jpg?w=300&#038;h=167" alt="ZKReadDB2 in Browser" width="300" height="167" /></a><p class="wp-caption-text">ZKReadDB2 in Browser</p></div>
<p>You notice I also added the pagination feature and worked with the window size. Maybe it would be an option to use a grid instead of the vbox/hbox to avoid ugly wraps like in the screenshot.</p>
<p style="text-align:justify;"><strong>Remarks:</strong></p>
<ul style="text-align:justify;">
<li>Dont forget to start the Java Derby DB (Services|Databases|Connect sample DB..) in Netbeans or you will get a <em>Error connecting to server localhost on port 1527 with message Connection refused: connect.</em></li>
<li>Without databinding in the previous part we could use the listbox sort feature (sort=&#8221;auto&#8221;). We loose this convenience once we use data-binding. Check the developers guide to implement such a function. But we also should do a reality check, do we want the browser to sort 10.000 rows ?</li>
</ul>
<p style="text-align:justify;"><strong>Where are we going from here:</strong></p>
<ul style="text-align:justify;">
<li>Implement the sort function (or maybe a filter that cuts down the number of records to display)</li>
<li>Add CRUD functionality</li>
<li>Find out if we can use session beans</li>
</ul>
<p>Enjoy the ride and stay tuned..</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/javadude.wordpress.com/510/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/javadude.wordpress.com/510/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/javadude.wordpress.com/510/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/javadude.wordpress.com/510/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/javadude.wordpress.com/510/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/javadude.wordpress.com/510/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/javadude.wordpress.com/510/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/javadude.wordpress.com/510/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/javadude.wordpress.com/510/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/javadude.wordpress.com/510/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javadude.wordpress.com&blog=3891833&post=510&subd=javadude&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://javadude.wordpress.com/2009/03/24/tutorial-reading-from-the-db-with-netbeans-and-zk-part-2/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c590146f757718a268c168a7eee0f53f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">devdude</media:title>
		</media:content>

		<media:content url="http://javadude.files.wordpress.com/2009/03/bv2009032417590033.jpg?w=300" medium="image">
			<media:title type="html">bv2009032417590033</media:title>
		</media:content>
	</item>
		<item>
		<title>Tutorial: Reading from the DB with Netbeans and ZK</title>
		<link>http://javadude.wordpress.com/2009/03/21/tutorial-reading-from-the-db-with-netbeans-and-zk/</link>
		<comments>http://javadude.wordpress.com/2009/03/21/tutorial-reading-from-the-db-with-netbeans-and-zk/#comments</comments>
		<pubDate>Sat, 21 Mar 2009 14:22:10 +0000</pubDate>
		<dc:creator>devdude</dc:creator>
				<category><![CDATA[tutorial]]></category>
		<category><![CDATA[how to]]></category>
		<category><![CDATA[jpa]]></category>
		<category><![CDATA[netbeans]]></category>
		<category><![CDATA[zk]]></category>

		<guid isPermaLink="false">http://javadude.wordpress.com/?p=490</guid>
		<description><![CDATA[After the first very basic tutorial that gets you started with the required plugins and settings (link), I will summarize in this tutorial how display data with zul using the JPA.
Requirements:

Netbeans 6.5 with a running derby DB and the sample database (customer table)
Installed ZK 3.6.0 plugin

Tutorial:
Content:
1. Start a new project
2. Create a new Entity Class [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javadude.wordpress.com&blog=3891833&post=490&subd=javadude&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p>After the first very basic tutorial that gets you started with the required plugins and settings (<a href="http://javadude.wordpress.com/2009/03/19/getting-started-with-zk-and-netbeans/" target="_blank">link</a>), I will summarize in this tutorial how display data with zul using the JPA.</p>
<p><em>Requirements:</em></p>
<ul>
<li>Netbeans 6.5 with a running derby DB and the sample database (customer table)</li>
<li>Installed ZK 3.6.0 plugin</li>
</ul>
<p><em>Tutorial:</em></p>
<p><em>Content:<br />
</em>1. Start a new project<br />
2. Create a new Entity Class from Database<br />
3. Create a Controller<br />
4. Create the table</p>
<p><span id="more-490"></span><strong>1. Start a new project</strong> (File|New Project|Category: Web|ZK360 Application)</p>
<p>Lets call it <em>ZKReadDB</em></p>
<div id="attachment_491" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.files.wordpress.com/2009/03/bv2009032117390022.jpg"><img class="size-medium wp-image-491" title="bv2009032117390022" src="http://javadude.files.wordpress.com/2009/03/bv2009032117390022.jpg?w=300&#038;h=204" alt="Netbeans: " width="300" height="204" /></a><p class="wp-caption-text">Netbeans: New Web Project</p></div>
<div id="attachment_492" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.files.wordpress.com/2009/03/bv2009032117400023.jpg"><img class="size-medium wp-image-492" title="bv2009032117400023" src="http://javadude.files.wordpress.com/2009/03/bv2009032117400023.jpg?w=300&#038;h=204" alt="Netbeans: New Web Project" width="300" height="204" /></a><p class="wp-caption-text">Netbeans: Project Name and Location</p></div>
<p>We find a complete web project skeleton with an empty index.zul file.</p>
<p>We need to some manual changes because the new project wizard does not ask for it. Open the project properties (by right click on the project title in the project explorer)<br />
- Choose the <strong>application server</strong> you want to use (from these configured in your NB). Seems the wizard just choose anyone.<br />
- The binary format <strong>JDK </strong>6 (if earlier version,before 1.5, you have problems compiling JPA methods or creating entity classes)</p>
<div id="attachment_493" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.files.wordpress.com/2009/03/bv2009032117410024.jpg"><img class="size-medium wp-image-493" title="bv2009032117410024" src="http://javadude.files.wordpress.com/2009/03/bv2009032117410024.jpg?w=300&#038;h=215" alt="Netbeans: Application Server" width="300" height="215" /></a><p class="wp-caption-text">Netbeans: Application Server</p></div>
<div id="attachment_494" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.files.wordpress.com/2009/03/bv2009032117420025.jpg"><img class="size-medium wp-image-494" title="bv2009032117420025" src="http://javadude.files.wordpress.com/2009/03/bv2009032117420025.jpg?w=300&#038;h=215" alt="Netbeans:: Source Level for JDK" width="300" height="215" /></a><p class="wp-caption-text">Netbeans: Source Level for JDK</p></div>
<p style="text-align:left;"><strong>2. Create a new Entity Class from Database </strong>(Right click project|New..|Persistence|Entity class from DB)</p>
<p>Exclude the related table to make the overall sourcecode for this tutorial less complex.<br />
Let the wizard create the Persistence Unit using Toplink for you. Default name: <em>ZKReadDBPU</em><br />
Place the class file in the package <em>data</em><br />
Leave the mapping options as default but use as collection type <em>java.util.list</em></p>
<div id="attachment_495" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.files.wordpress.com/2009/03/bv2009032118120026.jpg"><img class="size-medium wp-image-495" title="bv2009032118120026" src="http://javadude.files.wordpress.com/2009/03/bv2009032118120026.jpg?w=300&#038;h=204" alt="Netbeans: Entity Class from DB" width="300" height="204" /></a><p class="wp-caption-text">Netbeans: Entity Class from DB</p></div>
<div id="attachment_496" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.files.wordpress.com/2009/03/bv2009032118120027.jpg"><img class="size-medium wp-image-496" title="bv2009032118120027" src="http://javadude.files.wordpress.com/2009/03/bv2009032118120027.jpg?w=300&#038;h=196" alt="Netbeans: Select DB connection and tables" width="300" height="196" /></a><p class="wp-caption-text">Netbeans: Select DB connection and tables</p></div>
<div id="attachment_497" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.files.wordpress.com/2009/03/bv2009032118170028.jpg"><img class="size-medium wp-image-497" title="bv2009032118170028" src="http://javadude.files.wordpress.com/2009/03/bv2009032118170028.jpg?w=300&#038;h=196" alt="Netbeans: Entity Class" width="300" height="196" /></a><p class="wp-caption-text">Netbeans: Entity Class</p></div>
<div id="attachment_498" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.files.wordpress.com/2009/03/bv2009032118170029.jpg"><img class="size-medium wp-image-498" title="bv2009032118170029" src="http://javadude.files.wordpress.com/2009/03/bv2009032118170029.jpg?w=300&#038;h=146" alt="Netbeans: Persistence Unit" width="300" height="146" /></a><p class="wp-caption-text">Netbeans: Persistence Unit</p></div>
<div id="attachment_499" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.files.wordpress.com/2009/03/bv2009032118250030.jpg"><img class="size-medium wp-image-499" title="bv2009032118250030" src="http://javadude.files.wordpress.com/2009/03/bv2009032118250030.jpg?w=300&#038;h=196" alt="Netbeans: Mapping" width="300" height="196" /></a><p class="wp-caption-text">Netbeans: Mapping</p></div>
<p>Now we should have a Customer.java file in the package data with all the default JPA methods and members mapping the customer table.</p>
<p><strong>3. Create a Controller</strong> (Right click project|New..|Java Class)</p>
<div id="attachment_500" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.files.wordpress.com/2009/03/bv2009032118300031.jpg"><img class="size-medium wp-image-500" title="bv2009032118300031" src="http://javadude.files.wordpress.com/2009/03/bv2009032118300031.jpg?w=300&#038;h=204" alt="Netbeans: Controller Class" width="300" height="204" /></a><p class="wp-caption-text">Netbeans: Controller Class</p></div>
<pre class="brush: java;">
package data;

public class Controller {

}
</pre>
<p>Remark: You could add the controller code into a &lt;zscript&gt; tag directly into the zul file, but I wont recommend that for functionality of that extent. There are no automatic IDE features available while typing the code and it is hard to debug and maintain. Stick to the separation concept and keep the controller in its own classfile!</p>
<p>Now we need to add (finally) some functionality to the controller and the zul file:<br />
- the class needs to extend the Window class (<em>org.zkoss.zul.Window</em>)<br />
- a arraylist that the zul file can access via a getter<br />
- some persistence code to read all customer records (for the sake of the simple sample we place this in the constructor and we read all records)<br />
- import the required packages (Use &#8220;Fix Imports&#8221;)</p>
<pre class="brush: java;">
package data;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import org.zkoss.zul.Window;

public class Controller extends Window {

    List customers = new ArrayList();

    public Controller() {
        EntityManagerFactory emf;
        emf = Persistence.createEntityManagerFactory(&quot;ZKReadDBPU&quot;);
        EntityManager em = emf.createEntityManager();
        javax.persistence.Query q = em.createQuery(&quot;select c from Customer as c&quot;);
        customers = q.getResultList();
        em.close();
    }

    public List getCustomers() {
        return customers;
    }
}
</pre>
<p><strong>4. Create the table </strong>(index.zul)</p>
<p>Empty skeleton:</p>
<pre class="brush: java;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;window&gt;
    My ZK application
&lt;/window&gt;
</pre>
<p>Give the window an id and connect it to the controller class.</p>
<pre class="brush: java;">
&lt;window id=&quot;win&quot; use=&quot;data.Controller&quot;&gt;
</pre>
<p>Add a listbox by Drag and Drop from the palette, place it right after the &#8220;My ZK Application&#8221;.</p>
<p>Listbox skeleton:</p>
<pre class="brush: java;">
	&lt;listbox id=&quot;&quot; width=&quot;&quot; height=&quot;&quot;
                    onSelect=&quot;&quot;&gt;
	&lt;listhead&gt;
	&lt;listheader label=&quot;&quot;/&gt;
	&lt;listheader label=&quot;&quot;/&gt;
        &lt;/listhead&gt;
	&lt;listitem&gt;
	&lt;listcell label=&quot;&quot;/&gt;
	&lt;listcell label=&quot;&quot;/&gt;
        &lt;/listitem&gt;

    &lt;/listbox&gt;
</pre>
<p>Modify the listbox as follows:</p>
<pre class="brush: java;">
	&lt;listbox id=&quot;lb&quot; width=&quot;200&quot; height=&quot;300&quot;  &gt;
	&lt;listhead&gt;
	&lt;listheader label=&quot;name&quot; sort=&quot;auto&quot;/&gt;
	&lt;listheader label=&quot;email&quot;/&gt;
        &lt;/listhead&gt;
	&lt;listitem forEach=&quot;${win.customers}&quot; value=&quot;${each}&quot;&gt;
	&lt;listcell label=&quot;${each.name}&quot;/&gt;
	&lt;listcell label=&quot;${each.email}&quot;/&gt;
        &lt;/listitem&gt;
    &lt;/listbox&gt; 
</pre>
<p>There we go, run the project, it gets deployed and your favorite browser should open showing this:</p>
<div id="attachment_506" class="wp-caption alignnone" style="width: 310px"><a href="http://javadude.files.wordpress.com/2009/03/bv2009032119430032.jpg"><img class="size-medium wp-image-506" title="bv2009032119430032" src="http://javadude.files.wordpress.com/2009/03/bv2009032119430032.jpg?w=300&#038;h=167" alt="Result in Browser" width="300" height="167" /></a><p class="wp-caption-text">Result in Browser</p></div>
<p>Remarks:</p>
<ul>
<li>This is the most basic possible version, it lacks of any error handling and security.</li>
<li>The next exercise would be adding a detail view that offers CRUD functionality and databinding.</li>
</ul>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/javadude.wordpress.com/490/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/javadude.wordpress.com/490/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/javadude.wordpress.com/490/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/javadude.wordpress.com/490/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/javadude.wordpress.com/490/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/javadude.wordpress.com/490/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/javadude.wordpress.com/490/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/javadude.wordpress.com/490/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/javadude.wordpress.com/490/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/javadude.wordpress.com/490/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javadude.wordpress.com&blog=3891833&post=490&subd=javadude&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://javadude.wordpress.com/2009/03/21/tutorial-reading-from-the-db-with-netbeans-and-zk/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c590146f757718a268c168a7eee0f53f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">devdude</media:title>
		</media:content>

		<media:content url="http://javadude.files.wordpress.com/2009/03/bv2009032117390022.jpg?w=300" medium="image">
			<media:title type="html">bv2009032117390022</media:title>
		</media:content>

		<media:content url="http://javadude.files.wordpress.com/2009/03/bv2009032117400023.jpg?w=300" medium="image">
			<media:title type="html">bv2009032117400023</media:title>
		</media:content>

		<media:content url="http://javadude.files.wordpress.com/2009/03/bv2009032117410024.jpg?w=300" medium="image">
			<media:title type="html">bv2009032117410024</media:title>
		</media:content>

		<media:content url="http://javadude.files.wordpress.com/2009/03/bv2009032117420025.jpg?w=300" medium="image">
			<media:title type="html">bv2009032117420025</media:title>
		</media:content>

		<media:content url="http://javadude.files.wordpress.com/2009/03/bv2009032118120026.jpg?w=300" medium="image">
			<media:title type="html">bv2009032118120026</media:title>
		</media:content>

		<media:content url="http://javadude.files.wordpress.com/2009/03/bv2009032118120027.jpg?w=300" medium="image">
			<media:title type="html">bv2009032118120027</media:title>
		</media:content>

		<media:content url="http://javadude.files.wordpress.com/2009/03/bv2009032118170028.jpg?w=300" medium="image">
			<media:title type="html">bv2009032118170028</media:title>
		</media:content>

		<media:content url="http://javadude.files.wordpress.com/2009/03/bv2009032118170029.jpg?w=300" medium="image">
			<media:title type="html">bv2009032118170029</media:title>
		</media:content>

		<media:content url="http://javadude.files.wordpress.com/2009/03/bv2009032118250030.jpg?w=300" medium="image">
			<media:title type="html">bv2009032118250030</media:title>
		</media:content>

		<media:content url="http://javadude.files.wordpress.com/2009/03/bv2009032118300031.jpg?w=300" medium="image">
			<media:title type="html">bv2009032118300031</media:title>
		</media:content>

		<media:content url="http://javadude.files.wordpress.com/2009/03/bv2009032119430032.jpg?w=300" medium="image">
			<media:title type="html">bv2009032119430032</media:title>
		</media:content>
	</item>
		<item>
		<title>JPA and JDBC calls</title>
		<link>http://javadude.wordpress.com/2008/11/09/jpa-and-jdbc-calls/</link>
		<comments>http://javadude.wordpress.com/2008/11/09/jpa-and-jdbc-calls/#comments</comments>
		<pubDate>Sun, 09 Nov 2008 00:00:16 +0000</pubDate>
		<dc:creator>devdude</dc:creator>
				<category><![CDATA[java]]></category>
		<category><![CDATA[netbeans]]></category>
		<category><![CDATA[ejb]]></category>
		<category><![CDATA[jdbc]]></category>
		<category><![CDATA[jpa]]></category>
		<category><![CDATA[jsr220]]></category>
		<category><![CDATA[mysql]]></category>

		<guid isPermaLink="false">http://javadude.wordpress.com/?p=144</guid>
		<description><![CDATA[JPA &#8211; Java Persistence API
This JAVA programming framework is part of EJB3.0 in JEE5. It is very powerful and removes a truckload of work for todays enterprise developer. You manage the relation between classes and relational DB&#8217;s via ORM. Once you digest the concept, it become part of your toolset.
I come from a old-fashioned background [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javadude.wordpress.com&blog=3891833&post=144&subd=javadude&ref=&feed=1" />]]></description>
			<content:encoded><![CDATA[<div class='snap_preview'><br /><p><strong>JPA &#8211; Java Persistence API</strong><br />
This JAVA programming framework is part of EJB3.0 in JEE5. It is very powerful and removes a truckload of work for todays enterprise developer. You manage the relation between classes and relational DB&#8217;s via ORM. Once you digest the concept, it become part of your toolset.</p>
<p>I come from a old-fashioned background and always interest what runs under the hood and like to know about the manual way as well before indulging the &#8220;can-do-everything-easily&#8221; way.</p>
<p>So here my hommage to the &#8220;old&#8221; of directly accessing a DB. I am still using this approach for simple J2SE tools though ! I will talk about JPA more in detail soon.</p>
<p><strong>Open and access a MySQL DB from Java</strong></p>
<p>Establish a connection</p>
<p><em>String userName = &#8220;user&#8221;;<br />
String password = &#8220;********&#8221;;<br />
String url = &#8220;jdbc:mysql://localhost/db_sample&#8221;;<br />
Class.forName(&#8220;com.mysql.jdbc.Driver&#8221;).newInstance();<br />
con = (Connection) DriverManager.getConnection(url, userName, password);</em></p>
<p>Read from a table</p>
<p><em>Statement dbStatement = (Statement) con.createStatement();<br />
ResultSet dbResultSet = dbStatement.executeQuery(&#8220;Select * from table_name&#8221;);<br />
while (dbResultSet.next()) {<br />
String testField = dbResultSet.getString(&#8220;fieldname&#8221;);<br />
}</em></p>
<p>(Dont forget to cover both with try-catch&#8217;es and Netbeans will remind you of all the missing imports)</p>
<p>You see a number of potential flaws which gonna create trouble once you need to change it:<br />
- hardcoded user, password, DB<br />
- hardcoded table- and fieldnames<br />
Imagine the project time 100 with dozens of tables and 100&#8217;s of fields, thats where the headache starts&#8230; You know what I am talking about.</p>
  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/javadude.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/javadude.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/javadude.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/javadude.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/javadude.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/javadude.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/javadude.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/javadude.wordpress.com/144/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/javadude.wordpress.com/144/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/javadude.wordpress.com/144/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=javadude.wordpress.com&blog=3891833&post=144&subd=javadude&ref=&feed=1" /></div>]]></content:encoded>
			<wfw:commentRss>http://javadude.wordpress.com/2008/11/09/jpa-and-jdbc-calls/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/c590146f757718a268c168a7eee0f53f?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">devdude</media:title>
		</media:content>
	</item>
	</channel>
</rss>