Pavel Buzek's Weblog

All | JavaEE5 | netbeans
« Previous day (Nov 13, 2005) | Main | Next day (Nov 14, 2005) »
20051114 e hënë nëntor 14, 2005

Java EE 5 Persistence Demo


I gave you a short primer on Java EE 5 persistence in my last blog entry. Now it's time for a demo. I'll show you how to setup the persistence framework in web application and create a POJO class that represents data from a database table. Then I will execute an EJBQL query to get object from database. In the last step I will use the new JSF component palette to generate a page that displays object in table.

Step 1: Get the Software

I'll be using a NetBeans Java EE 5 daily build from November 13 and build 26 of GlassFish open source Java EE application server, you also need JDK 1.5.

I should repeat that support for Java EE 5 is NOT part of NetBeans 5.0, it will be in the next release of NetBeans and is now being developed on a "javaee5" branch.

Register GlassFish in NetBeans using Tools>Server Manager menu. To register GlassFish use the Sun Java Systems Application Server as a server type. NetBeans will help you to create a new domain for the server, use the "Create Personal Domain" option.

Step 2: Web Application with Persistence Support

Create a new web application project, select GlassFish server and set J2EE version "Java EE 5". Click next and add Java Server Faces support.

Now let's add persistence support into this project. This will be just a few clicks in a wizard, but since I did not cover the persistence unit in the intro let me first describe it here.

Persistence unit defines where and how to persist your classes. The definition of persistence unit consists of:

In this example we will only specify the data source. We will use defaults for everything else.

We could specify the parameters of data source directly in your persistence.xml, setting properties like jdbc.connection.string, jdbc.driver, jdbc.user, etc. But in this example I will be using a data source that is defined by the application server, the persistence unit will just reference it by its name. This will make it easier to move the application from one application server and database to another, for example between development, test and production environments.

Now back to our demo. Select menu File>New File (Ctrl+N). Select Persistence Unit template in category Persistence:

Type the name of persistence unit ("demo1"), and keep the default for provider:

Persistence units are defined in persistence.xml file. The content of generated file is:

  <?xml version="1.0" encoding="UTF-8"?>
  <persistence xmlns="http://java.sun.com/xml/ns/persistence">  
    <persistence-unit name="demo1" transaction-type="JTA">
      <jta-data-source>jdbc/__default</jta-data-source>
      <properties/>
    </persistence-unit>
  </persistence>

Let's keep the default name of data source jdbc/__default for the demo. Normally you'd go to server admin tool and setup a data source there. But GlassFish has a data source with name jdbc/__default and a derby database connection pool registered. Setup up of database is the next step.

Step 3: Setup the Database

GlassFish bundles derby open source database and this is what I will use for this demo. NetBeans has a module that supports derby. Download the "Derby Database Support" module from the development update center. Use menu Tools>Update Center.

First, start the database using menu Tools>Derby Database>Start Derby Server. Then connect to the database:

The data source jdbc/__default in application server uses the following database URL: jdbc:derby://localhost:1527/sun-appserv-samples;create=true. Use sa for both user name and password and on the next panel select schema APP. This will add a the new connection in Runtime tab and you can execute database scripts on it:

Note the new SQL editor with syntax highlighting, toolbar, etc. that we added in NetBeans 5.0:

Here is the complete script for the table and for inserting some data (insert each line separately). Refresh the list of tables and select View Data from popup menu on DIVECHARTERS table to verify everything is fine. Yes, these are some cool scuba diving trips with my favorite dive shop in Beaufort, NC :-)

Ok, we are done with the database.

Step 4: Persistence Java Class

Click New.. (Ctrl+N) and select Persistence Entity template in category Persistence. Type class name "Divecharters" and package name "data" and click Finish.

Now add properties for table columns:

@Entity
public class Divecharters {
    private int id;
    private Date departure;
    private String boat;
    private String diveSite;
    private String description;
    private int maxDepth;
    private double price;
    private int capacity;
    ...
}

Use menu Refactor>Encapsulate Fields to create getters and setters for these fields.

Later on NetBeans will support generation of persistence classes from DB tables, similarly as the "CMP from Database" in NetBeans 4.1 and 5.0.

Step 5: Display Objects in JSF Page

We will create a JSF managed bean that will select all instances of Divecharters using EJBQL query. Then we will edit the welcomeJSF.jsp to display them.

Use New.. (Ctrl+N), select the template JSF Managed Bean in category Web. Type class name "PersonController", package "beans" and set scope to "session".

We will use EntityManager the get the persistent data. EntityManager is the central access point to the persistence API. It allows you to create and run queries, persist objects, manage transactions, etc.

The server will inject EntityManager for the PersistenceUnit we defined in Step 2. We will use it to query for all instances of Divecharters class:

public class PersonController {
    
    @PersistenceContext(unitName="demo1")
    EntityManager em;
    

    public List getCharters() {
        return em.createQuery("select object(d) from Divecharters as d").getResultList();    
    }
    ...

This means that our JSF managed bean PersonController will have a property charters. We can now add a JSF data table into welcomeJSF.jsp to render the list of charters. We started to work on a set of templates and palette items to simplify development and prototyping of simple CRUD applications. This is experimental at this point but it comes handy for the demo (give me feedback!). The first preview are two JSF palette items: JSF Form and JSF Data Table:

The code generated in page looks like this:

    <f:view>
        <h:form>
            <h1><h:outputText value="List"/></h1>
            <h:dataTable value="#{PersonController.charters}" var="item">    
                <h:column>
                    <f:facet name="header">
                        <h:outputText value="Id"/>
                    </f:facet>
                    <h:outputText value="#{item.id}"/>
                </h:column>
                <h:column>
                    <f:facet name="header">
                        <h:outputText value="Departure"/>
                    </f:facet>
                    <h:outputText value="#{item.departure}"/>
                </h:column>
         ...

Run the application:


( Nën 14 2005, 01:38:50 MD EST ) Permalink Comments [28]

Download NetBeans IDE

Calendar

RSS Feeds

Recent Entries

Blogs

Search

Navigation

Referers