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:

  • Name and description.
  • Provider: the implementation of persistence API, such as Toplink, Hibernate, etc. If you leave this empty the server will choose the default.
  • Data source, i.e. where the data will be stored and what transaction model will be used.
  • Mapping file is an xml file that defines mappings between database and Java classes. This is useful if you need to define the mapping (we will not do this) and if you do not want to use annotations.
  • A set of classes that this persistence unit applies to. One Java EE module can use multiple persistence units, for example to store data to several different data sources. If you omit this all classes in module will belong to the persistence unit.
  • Properties: a set of name - value pairs of properties. The semantics of these is defined by the provider.

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="">  
    <persistence-unit name="demo1" transaction-type="JTA">

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:

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 {
    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:

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

Run the application:


Pavel - This is awesome. I haven't had time to step through it yet with a build, but it looks really cool.

One question: When you wrote, "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." did you mean in a later build? In other words, the ability to generate the persistence classes will be in, right?

We won't have to wait for :-)

Posted by Gregg Sporar on nëntor 15, 2005 at 06:05 PD EST #

Greg, it (DB->Java) will be there when we first release NetBeans with Java EE 5 persistence support (i.e. In fact I hope to have it much earlier, but I cannot promis a date. I will blog about it when it's ready :-).

Posted by guest on nëntor 15, 2005 at 06:25 PD EST #

Yes indeed, this is awesome!
Eventually, would be really nice to right click on a Domain Model object and be able to request the generation of all CRUD artifacts (a la RoR).

One thing, I keep getting the following exception in the JSP editor:

javax.swing.text.BadLocationException: Misuse at 34 at org.netbeans.editor.ext.html.HTMLSyntaxSupport.getNextElement( at org.netbeans.editor.ext.html.SyntaxElement.getNext( at org.netbeans.modules.web.core.syntax.folding.JspFoldManager.generateFolds( at org.netbeans.modules.web.core.syntax.folding.JspFoldManager.updateFolds( at org.netbeans.modules.web.core.syntax.folding.JspFoldManager.access$200( at org.netbeans.modules.web.core.syntax.folding.JspFoldManager$ [catch] at

Thanks again for the great work!

-- Pierre

Posted by guest on nëntor 16, 2005 at 12:10 PD EST #

Pierre, I am thinking about the CRUD generation. I started to do it piece by piece, the controller generation is still missing.

Thanks for actually trying this! Please ignore the exception. I know this is annoying but should be harmless. I need to merge from trunk where this is fixed.

Posted by guest on nëntor 16, 2005 at 01:32 PD EST #

Pavel, Thanks for the blog. I so want to be playint with Java 5 EE, at work we're still on J2EE 1.3 and it doesn't look like 1.4 will be used any time soon. I love NB, and I just installed Glassfish, so I guess I will instally the NB JavaEE5 version.

Posted by Will on nëntor 17, 2005 at 01:33 MD EST #

Note that needs the @Id annotation, as described in the example in the first part of the demo. That is, @Id(generate = GeneratorType.AUTO) public int getId() { return id; } ==Leonard

Posted by Leonard Sitongia on nëntor 21, 2005 at 10:42 PD EST #

I am unable to start the Derby server from the Tools menu. Derby Database Process console shows the message : java.lang.NoClassDefFoundError: and Exception in thread "main" I am using netbean IDE 5.0 build 200511212300 Can you please help? Moreover, can you provide instructions for using it with MySql

Posted by Vimal on nëntor 23, 2005 at 03:55 MD EST #

Netbeans has a BIG bug under Windows. It's not allowed that the folder name contains spaces. Go to the file "netbeans.conf" in the folder "etc" and change the netbeans_default_userdir to a name without spaces.

I want to say to the developers thank you for a sleepless night.

Another point ( it's not a bug it's a feature ):

What should I change so that the application always show me the newest data particularly with regard to an UPDATE in the database ?

Finally, Pavel thank you for the great article. Unfortunately, it's very hard to find this kind of information.

Posted by guest on nëntor 24, 2005 at 09:25 MD EST #

Hi Pavel,

Thank you very much for all this info. It really helps a lot.

But I still have some problems when I deploy de application using EJB 3.

The error message is:
"Deploying application in domain failed; Error loading deployment descriptors for teste7 Line 4 Column 22 -- archive Teste7-EJBModule.jar in deployment descriptor file META-INF/ejb-jar.xml Error loading deployment descriptors for teste7 Line 4 Column 22 -- archive Teste7-EJBModule.jar in deployment descriptor file META-INF/ejb-jar.xml"

Do somebody have any idea?

Thank you very much,

Posted by Yara on nëntor 28, 2005 at 11:19 MD EST #

Anyone have any idea why I am getting this error stack: javax.servlet.ServletException: java.lang.IllegalStateException: Unable to retrieve EntityManagerFactory for unitName demo1 javax.faces.webapp.FacesServlet.service( sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke( sun.reflect.DelegatingMethodAccessorImpl.invoke( java.lang.reflect.Method.invoke($ Method) com.sun.enterprise.web.WebPipeline.invoke( org.apache.coyote.tomcat5.CoyoteAdapter.service( com.sun.enterprise.web.connector.grizzly.ProcessorTask.doProcess( com.sun.enterprise.web.connector.grizzly.ProcessorTask.process( com.sun.enterprise.web.connector.grizzly.ReadTask.executeProcessorTask( com.sun.enterprise.web.connector.grizzly.ReadTask.doTask(

Posted by Peter Boivin on nëntor 30, 2005 at 12:15 MD EST #

Problem solved by installing newer version of Glassfish....

Posted by Peter Boivin on dhjetor 01, 2005 at 01:57 MD EST #

Hi, Yara. I have solved that problem by deleting "enterprise-beans" tag.

Posted by Naoki Kishida on dhjetor 03, 2005 at 07:03 PD EST #

Additionally, I had to move the code that retrieve EntityManager to a SessionBean. It wasn't injected on the code of JSF ManagedBean.

Posted by Naoki Kishida on dhjetor 04, 2005 at 07:58 MD EST #

I created a Flash screencast/demo inspired :) by this blog entry of yours, for a local free and open source event called FOSS.IN/2005, and was demoed in the Sun pod. The flash presentation is linked off Binod's blog. With NetBeans 5.0 Java EE 5.0 branch and GlassFish , it surely is, easy to develop Java EE Persistence apps. Many thanks for this entry and please continue the good work. --Siva.

Posted by Sivakumar Thyagarajan on dhjetor 05, 2005 at 03:00 PD EST #

Hi Pavel Thanks for this instruction, I am not so familiar with the configurating of this IDE. So I ran into a problem on step 1 There is no Server Manager menu under the Tools menu. Even the help told me so. So can you give me the lokation to register the glassFish dataBase? I downLoaded version 200512152300, your recomended version was not available anyMore Thanks Greetz Gerard Doets

Posted by gerard doets on dhjetor 17, 2005 at 07:06 PD EST #

I might found the problem I have the developper netbeans editon installed I'' look for the EE

Posted by Gerard Doets on dhjetor 21, 2005 at 08:55 PD EST #

Important note!!
There is bug in netbeans that puts the persistence.xml file in the wrong folder (should be in WEB-INF/classes/META-INF)
See this thread:
And this bug report:

Posted by Warren Strange on janar 14, 2006 at 04:30 MD EST #

Sory to say that there remains a problem with this Server Manager menu under the Tools menu. I am afrait netbeans is not the way 4 me, please remove my entries here. I had more luck with the demo from bea. Thanks Bye

Posted by Gerard Doets on janar 18, 2006 at 08:36 PD EST #

Hello Pavel,

Very nice and easy demo. A note about the datatable palette though.

The datatable creation wizard requires a bean name when it's actually looking for a class and requires a backing bean for the data where only a bean should be asked for. A backing bean, by JSF specification, is a managed bean that provides UIComponent instances for the JSF tag, which is not the case here, a simple managed bean works.

Posted by Simon Lessard on janar 20, 2006 at 08:33 PD EST #

Hi Pavel, I liked your demo. It helped me understand the ejb3/faces mechanism very quickly. I was wondering though how would I go about updating the data? I tried using the injected EntityManager for updating as well as querying but I keep getting a TransactionRequired exception of: Error marking externally managed transaction for rollback However, if I insert "em.getTransaction().begin()" into my code I then get a ServletException of: Cannot use an EntityTransaction while using JTA. Obviously my reasoning is flawed somewhere. What is the proper procedure of obtaining the current JTA transaction to be able to update the data? Thanks for any insights you can provide.

Posted by William Mann on janar 22, 2006 at 07:20 MD EST #

JSF component palette-- Pavel, thanks for the wonderful blog. I am using Netbean 5 RC2 on Windows XP, but I can't see a JSF component palette with my IDE. Is there a special plug in install to get the palette? Thanks! Steve

Posted by Steve on shkurt 10, 2006 at 06:02 PD EST #

This is the exception that i am getting when i am trying to add some data to an entity bean.can u help me out? javax.ejb.EJBException com.sun.ejb.containers.BaseContainer.processSystemException( com.sun.ejb.containers.BaseContainer.completeNewTx( com.sun.ejb.containers.BaseContainer.postInvokeTx( com.sun.ejb.containers.BaseContainer.postInvoke( com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke( com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke( $Proxy64.addAppointment(Unknown Source) com.ail.AddAppointments.processRequest( com.ail.AddAppointments.doPost( javax.servlet.http.HttpServlet.service( javax.servlet.http.HttpServlet.service( sun.reflect.GeneratedMethodAccessor102.invoke(Unknown Source) sun.reflect.DelegatingMethodAccessorImpl.invoke( java.lang.reflect.Method.invoke($ Method) com.sun.enterprise.web.WebPipeline.invoke( com.sun.enterprise.web.VirtualServerPipeline.invoke( org.apache.coyote.tomcat5.CoyoteAdapter.service( com.sun.enterprise.web.connector.grizzly.ProcessorTask.invokeAdapter( com.sun.enterprise.web.connector.grizzly.ProcessorTask.processNonBlocked( com.sun.enterprise.web.connector.grizzly.ProcessorTask.process( com.sun.enterprise.web.connector.grizzly.ReadTask.executeProcessorTask( com.sun.enterprise.web.connector.grizzly.ReadTask.doTask(

Posted by sujal on mars 01, 2006 at 01:35 PD EST #

The first steps towards repairing your relationship with the gods is to::::::::: 1. Understand they instruct the computer to "role play" in an attempt to confuse you:::it's ALWAYS the computer addressing you. Their goal is to cost you additional YEARS of your life by using this tactic to confuse you. Always be aware of this tactic and eventually they will give up and allow this step to be taken. 2. Differentiate between your thoughts and when they are thinking through you. 3. Be resigned to be a good person who will never engage in evil again even if ordered and they will stop trying to corrupt you, allowing this very big step to be taken. 4. Decide that you are going to follow the path, fix your relationship with the gods be devoted to your new life. Atlanta's I-20 Racer, 250_mph_motorcyclists. It was surreal, like Close Encounters of the Third Kind::::Floating lights zipping towards me faster than anything I've ever seen Oakland is the final 20th century professional sports-based bastion of institutionalized racism in California. California is evil. California subducts first. Oakland is the final 20th century professional sports-based bastion of institutionalized racism in California. Oakland is the last city in California which has a major sports complex on the edge of the ghetto. Staples Center replaced the LAForum in Inglewood and PacBellPark replaced Candlestick in BayView/Hunter'sPoint. Restricting tickets in Oakland has hurt blacks by rejuvinating this market for scalpers. I'd like to note the absence of black players on the A's and how this deliberate message starkly contrasts to the SFGiants. In their reports the media intentionally ignored the reality of this case:::He didin't want to go home. Interviewed a child therapists who commentted consistant with her profession. Hey lady!!! You woud have gotten thousands of years had you not chosen this line of work!!!! Keep prescribing that poison (they say too many of them still think they're earning by doing so!!!). Likely they were peaking him euphoircally homosexually, and they say when it happens pre-pubescent like that it means something. Possibility #2 is he found out his parents complied fully with what they were told, that they sabotaged their children's lives intentionally because they would never defy and got the hell out out of self-preservation. (It also is the reason for all the elder neglect/abuse as well.) Like so many others Mom may have complied when asked to sabotage their children's lives, to go to the grocery store and buy the specific products laced with the hormone growth poison (explosion of "big people" in last 40 YEARS!!!), totally unncecessary because Artificial Intelligence can accomplish these results (and all others, incuding AIDS:::::The gods instructed their clones to create AIDS as punishment for the hedonism of the 60s and 70s) yet still important for justification, justification an important dynamic for the sake of positioning; justification, scapegoatting and making one pay for the benefit of another typical organizational policy. So, assuming foul play wasn't an issue, the numbers would be very telling::::: 1. Most IF NOT ALL girls left because they found out their parents were sell-out whores who betrayed their children. It is very rare when they peak females like they do males. 2. Boys potentially could be peaked euphorically for it is JUSTIFIABLE!!! They suggest they matched the two, they told the child this man was the person the gods wanted him with so he went with him. What percentage is foul play an issue? 10%? 20%? So over half of the three-fourths of missing kids do the right thing by getting out, escaping an abusive parent who falls for temptation and obeys absolutely??? Considering that hormone growth poison in the designated grocery products will make them gargantuon, 1'-2' and 100lbs bigger than they should be, I'd argue they did the right thing (wild profits in this industry was "the rope", temptation for the disfavored investor who incurred evil which limited their time). The girls end up with broken hearts, crushed by their own parents. In other cases after making some progress the girls arrange for a new home telepathically and the girls escape to a healthy environment conducive to growth or directly off Planet Earth, sometimes with the parent's assistance. Leaving a disfavored household is the best thing that could happen to them. They say (my family's daughter) needs to get out of this enviornment or she won't have a chance, but unfortunately she has a legacy of gosip mongering which is going to be a big, big hurdle to overcome. So what's the purpose of parental betrayal? Did the gods want disposable generations from the 20th century? Was this important during the generations in which we became technological? Is the Apocalypse right around the corner and they needed to justify the deterioration of society, necessitating employing these deceptive tactics to the undesirable??? More than a few cultures agreed December 21, 2012 was going to be The End!!!!! Does California subduct first? "Hip-hop fucked"======================= (equals) < ifuckgod(dot)com > 11/27 11:09:35 1. Mysoginistic, a MAJOR scourge of blacks (elder women of earth will never support, not even your own foremothers) 2. Masculinizes the women ("THAT MEANS IT'S BAD FOR YOU!!!") 3. Makes violence socially acceptable. The gods use the United States to hurt the disfavored, at home and abroad, for it is the goal of redwhite&blue::: 20th century welfare hurt the black community very, very badly. There was too many abuses of the system and its legacy is still felt today. There will come a time that will be a CRUCIAL moment in the history of black america (whether it is a critical time for everybody remains to be seen). When that era arrives the gods will instruct the United States to pay black people reparations, and it may be as much as a million dollars for every man, woman and child. Refuse it. This is an act of preditation. The gods hate Africans, evident by the sorry state of the people in the United States and back in the motherland. This may ba a choice between going and the money. Understand how the gods use greed and materialism against you:::::Blacks wallow in materialiam, incurring evil and costing themselves time. And when their time DOES come they will be granted reparations immediately prior, further limiting the number of Africans who ascend. The day IS coming when they will grant reparations, and the amount will be staggering, another tactic to ensure you fail in the quest to ascend into heaven. And many of the disfavored blacks will blow it all; the gods will push them into spending it friviously or losing it in their casinos. Woman obeyed voices told her to throw children < off_a_balcony > 11/28 22:15:27 Woman obeyed voices that told her to throw her children off a balcony in Oakland. This incident and others like it are clues to individuals like like my family who otherwise would never defy. Similarity between the names "Santa" and "Satan" no_coincidence The Biblical account of Noah's flood was regional to the disfavored Mediterrean (water levels lowered because of the ice age, habitation ocurred at seaside), peoples whom the gods scapegoatted when they pushed them into the evil that justified the flood, behavior similar to that which we are witnessing today. Because they have leveled the playing field for all people (purebloods and mongrels) in the decades prior to the 21st century is a clue they will end globally this time (westernization, materialism, immigration/interracial, homosexual, access to disturbing media, desensitization, etc). Decent women don't engage in these pursuits. < _I_FUCK_GOD > 12/21 15:17:40 Beer is a corruptor and a dumping ground 4 men < _I_FUCK_GOD > 12/21 15:09:19 professional sports, video games, car racing/fixing up cars, pornography, drinking, gambling, etc. Decent women don't engage in these pursuits. In the last 40-50 years the gods have engaged in a process which masculinized women, including casual sex, partying, partifcipatory sports and women's prisons. god fucks the disfavored, plays the role of evil < ruining_life_on_Earth > 12/21 17:54:31 And all your forefathers were either pushed into their offenses or they complied and did it voluntarily. So much of this mind poisoning social "progressiveness" was initiated in California. In a couple of decades it pervaded east into the heartland AMONG THE MASSES, widespread instead of isloated. Gay acceptance/marriage, bi-racial acceptance, casual drug use/sex, cable TV, etc. So many things weren't present in the heartland decades ago. Because they are favored. Contrary to appearances, contrary to popular perception their favor got them extra time. In California the gods hurt the disfavored with this abuse right off the bat. California is favored. It is the land of the gods, and when they disfavored invade, as they did during the gold rush, the gods strike back. The gods pushed them into coming, told others, for only the disfavored are misled this way. Soon they scapegoatted these disfavored's descendants when the gods exported their wicked, sick sub-cultures to the rest of the nation. One day they will punish these descendants. California subducts first. And those who have gone will get less time. Expect similar reverse positioning in the Jesus issue. This is typical of the positioning of the gods. It's crucial that you begin to think correctly. There is no such thing as a Christian god and there never was. Be god-fearing.

Posted by Emotional whore on janar 26, 2007 at 10:22 PD EST #


Posted by 55 on qershor 03, 2007 at 09:35 MD EDT #

excuse me.Very beautiful post, before I have mistaken to write.

Posted by 55 on qershor 03, 2007 at 09:38 MD EDT #

whom ever wrote this statement < _I_FUCK_GOD > is such an idiot, amazing how people can get be such stupid arrogant with the little information that they have.

Posted by Ahmed Ghali on dhjetor 24, 2008 at 04:16 MD EST #


Posted by a on janar 09, 2009 at 03:29 MD EST #

very nice tutorial.
Got a supplement for you.
JEE skeleton project in maven 2 deployable on Glassfish


Posted by Marc de kwant on nëntor 03, 2009 at 10:40 MD EST #


Posted by kkkkk on shtator 27, 2010 at 06:42 PD EDT #

Post a Comment:
  • HTML Syntax: NOT allowed



« prill 2014