Hello JPA World!

After much discussion, I was able to finally create a simple "Hello JPA World" example that uses Java Persistence API (JPA) to store and retrieve data from JavaDB from a Servlet deployed on GlassFish V2 b50 using NetBeans IDE 5.5.1. This blog describes the steps, in detail, on how to create this sample.

  1. In NetBeans IDE, create a new Web project and name it as "HelloJPA".
  2. Create an Entity class. Right-click the project, select 'New', 'Entity Class ...'. Specify the values as shown below:

    1. Create a new Persistence Unit by selecting 'Create Persistence Unit ...' and entering values as shown below:



      and click on 'Create'.

    and click on 'Finish'.

  3. Expand 'Configuration Files', open 'persistence.xml', click 'Add Class ...', select 'server.Company' and click on 'OK'. The 'persistence.xml' will look like:

    <?xml version="1.0" encoding="UTF-8"?>
    <persistence version="1.0"
        xmlns="http://java.sun.com/xml/ns/persistence"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
        <persistence-unit name="HelloJPAPU" transaction-type="RESOURCE_LOCAL">
            <provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider>
            <non-jta-data-source>jdbc/sample</non-jta-data-source>
            <class>server.Company</class>
            <properties>
                <property name="toplink.ddl-generation" value="drop-and-create-tables"/>
            </properties>
        </persistence-unit>
    </persistence>
  4. Add the following fields to the newly generated 'Company.java':

    private String companyName;
    private float price;
    private float change;
    private float percentChange;
    private String lastUpdated;
  5. Generate getters/setters for each field by selecting the newly added fields, right-click on the selected text, select 'Refactor', 'Encapsulate Fields ...' and choose the getter/setters for each field as shown below:

  6. Add a constructor to 'Company' class as follows:

    public Company(String companyName, float price, float change, float percentChange, String lastUpdated) {
        this.companyName = companyName;
        this.price = price;
        this.change = change;
        this.percentChange = percentChange;
        this.lastUpdated = lastUpdated;
    }
  7. Change the toString method in Company to:

    return "server.Company[id=" + id + ", lastUpdated=" + lastUpdated + "]";
  8. Add a new Servlet by right-click on the Project, select New, 'Servlet ...' as shown below:



    and click on 'Finish'.
  9. Update the generated Servlet template code such that it looks like:

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        beginHTML(out);
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("HelloJPAPU");
        EntityManager em = emf.createEntityManager();

        em.getTransaction().begin();
        out.println("<h1>Hello JPA World!</h1>");

        Company c = new Company("AAA Co", (float)10.0, (float)2.0, (float)10.0, new Date().toString());
        em.persist(c); // persisting to the source
        em.getTransaction().commit(); // now committed

        List list = em.createQuery(
            "select c from Company c where c.companyName = :companyName")
            .setParameter("companyName", c.getCompanyName()).getResultList();

        out.println("<b>Total Companies: " + list.size() + "</b><br>");
        for (int i=0; i<list.size(); i++) {
            out.println((Company) list.get(i) + "<br>");
        }

        endHTML(out);
    }

    void beginHTML(PrintWriter out) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Hello JPA World!</title>");
        out.println("</head>");
        out.println("<body>");
    }

    void endHTML(PrintWriter out) {
        out.println("</body>");
        out.println("</html>");
        out.close();
    }


    Fix the imports by using 'Alt+Shift+F' default keyboard shortcut.
  10. Right-click on the Project, select 'Properties', 'Run' Categories, change the Relative URL to '/Hello'.
  11. And that's it! Hit the Green button to run the project or the default keyboard shortcut of 'F6'. After re-loading the page twice, the following output will be seen in the browser window:


 

Technorati: jpa glassfish netbeans

Comments:

Hi Arun, Your blog is a great source of information. Keep up the good work. I have one question regarding JPA - Any idea if I can use JPA with SQL Server 2005 (Express or Standard edition). If so, what is the JDBC driver that supports this. I would appreciate if you could blog on the same. Thanks.

Posted by Kris on July 01, 2007 at 08:18 PM PDT #

Kris, thanks for the comments. Googling for "JDBC driver for SQL server" gave me the link to "http://msdn2.microsoft.com/en-us/data/aa937724.aspx". You can download the JDBC driver for SQL server from this link. With that, in step 2.1 instead of selecting the pre-defined data source, just scroll down and you'll see an option to add a new driver. Rest of the steps should just fall in place. Let me know if you need more details on that and I can write a more detailed entry.

Posted by Arun on July 02, 2007 at 12:00 AM PDT #

Hi Arun, Thanks for your prompt response. I really appreciate it. I have made use of the MS JDBC driver a while ago and it works without a problem for JDBC related code. However when I tried to make use of JPA related functionality it did not work. But this was a few months back and I can't say I have tried it recently. I will try it once again. But if you do have time, I think it would be a nice post to cover all the major databases - Oracle, SQL Server and DB2 with a JPA example. Just a thought. Thanks, Kris

Posted by Kris on July 03, 2007 at 01:02 PM PDT #

[Trackback] The jMaki tutorial from SWDP explained the different approaches to load your own data into a jMaki widget. The jMaki widget models have formalized since then and so the code there no longer works. This TOTD explains how a combo...

Posted by Arun Gupta's Blog on August 29, 2007 at 11:21 PM PDT #

Hi Arun,
At first i like to appriciate for good work. I am new JPA. I want to use it with jsp.I did some work on that but unable to get good result.So can you please provide me some example on JPA. It will be great help since iam searching for it from 4 days but unable to get good resource. Because iam an example guy please provide me an example also.

Thanks
suraj

Posted by suraj on November 09, 2007 at 11:23 PM PST #

Suraj, Several examples of JSP using JPA are available at: http://blogs.sun.com/arungupta/tags/jpa

Let me know if you have a specific question.

Posted by Arun Gupta on November 09, 2007 at 11:35 PM PST #

[Trackback] &quot;sakila&quot; is the sample database shipped with MySQL (pronounced as my ess-kew-ell). In the context of Sun Microsystems announcing the agreement to acquire MySQL, I'd like to dedicate this entry to show how this sample database can be exposed a...

Posted by Arun Gupta's Blog on January 23, 2008 at 08:46 PM PST #

This is wonderful..thanks ..Arun

I was wondering which approach would be better.

1. First create entity class and then database from those entity class or
2. Create entity class from database.

Is there any good discussion/thread out there which explains the prons and cons of both of these scenarios?

Thanks
Jessica

Posted by Jessica on March 01, 2008 at 12:11 PM PST #

Just wanted to share this....on Netbeans 6.0, when you run this app, it will give you this error

Caused by: Exception [TOPLINK-0] (Oracle TopLink Essentials - 2.0 (Build b58g-fcs (09/07/2007))): oracle.toplink.essentials.exceptions.IntegrityException
Descriptor Exceptions:
---------------------------------------------------------
Exception [TOPLINK-63] (Oracle TopLink Essentials - 2.0 (Build b58g-fcs (09/07/2007))): oracle.toplink.essentials.exceptions.DescriptorException
Exception Description: The instance creation method [server.Company.<Default Constructor>], with no parameters, does not exist, or is not accessible.
Internal Exception: java.lang.NoSuchMethodException: server.Company.<init>()
Descriptor: RelationalDescriptor(server.Company --> [DatabaseTable(COMPANY)])

Adding an empty constructor in Company.java solves the issue.

Thanks
Jessica

Posted by Jessica on March 01, 2008 at 01:25 PM PST #

Running this code after a fresh install of Netbeans 6.1 gave me the error:

java.lang.IllegalArgumentException: Object: server.Company[id=null, lastUpdated=Sat Mar 08 09:43:17 EST 2008] is not a known entity type.

I added a default constructor to server.Company, but I still receive this error.

Posted by Ben on March 07, 2008 at 10:43 PM PST #

Restarted server and it works. Go figure.

Posted by Ben on March 07, 2008 at 10:46 PM PST #

Hi Arun,

I am new to EJB3 and Iam doing a project on EJB3 this semester. your article helped me to understand basics. thanks for this.

I would like to request you if you can provide me any details for using mysql instead of javaderby for EJB3 using glassfish on Netbeans.
My Problem is Iam unable to understnad about database part. Do I need to add it to connection resource in server console or i can go through some database setting on netbeans ide.

Plz clear me..
thanks a lot in advance

regards
abishek kumar.

Posted by Abishek Kumar on March 18, 2008 at 09:38 AM PDT #

Thanks a lot for this tutorial! It's really clear.

I'm using Eclipse, MySQL 5.0, GlassFish V2 instead of NetBeans and Derby.

To connect to MySQL I define a MySQL JDBC Ressource and call it jdbc/mysql_resource. I had to use this in persistence.xml ( had to define a non-jta-data-source called jdbc/mysql_resource as well as classes )

Posted by Tony on March 24, 2008 at 09:06 AM PDT #

Just forgot I define the MySQL JDBC Resource in the glassfish administration console.

Posted by Tony on March 24, 2008 at 09:08 AM PDT #

I'm curious about the "non-jta-datasource" tag in your persistence.xml that has the same value ("jdbc/sample") you entered in your gui tool. Does this "data-source" property exist in some external xml? How is "jdbc/sample" used?

Posted by Joe Kingston on April 10, 2008 at 06:08 AM PDT #

[TopLink Info]: 2008.03.06 09:46:25.640--ServerSession(3668766)--TopLink, version: Oracle TopLink Essentials - 2.0 (Build b58g-fcs (09/07/2007))
Exception Description: Cannot acquire data source [data_source].
Internal Exception: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial)

Posted by anonymus on April 29, 2008 at 05:16 PM PDT #

can any1 figureout wat the prob is...am using jpa wid toplinks

Posted by anonymus on April 29, 2008 at 05:18 PM PDT #

Just forgot I define the MySQL JDBC Resource in the glassfish administration console.

Posted by laptop batteries on November 27, 2008 at 08:58 AM PST #

It worked for me with NetBeans 6.1 as well. Nice example.

But I cannot understand lines about how to query the DB using entity manager as given below in Hello.java servlet class
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
Company c = new Company("AAA Co", (float)10.0, (float)2.0, (float)10.0, new Date().toString());
em.persist(c); // persisting to the source
em.getTransaction().commit(); // now committed

List list = em.createQuery(
"select c from Company c where c.companyName = :companyName")
.setParameter("companyName", c.getCompanyName()).getResultList();

\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*

A Good explantion would have helped beginners like me.

Some reference also might help.

Thanks and Wishes

Posted by Harish Vembu on January 06, 2009 at 03:15 AM PST #

Harish, Glad you liked the article. Please google on JPQL and you'll find tons of reference on how to use the query language that can be used with DB entity manager.

Posted by Arun Gupta on January 06, 2009 at 03:45 AM PST #

Instead of creating EntityManger as:

EntityManagerFactory emf = Persistence.createEntityManagerFactory("HelloJPAPU");
EntityManager em = emf.createEntityManager();

it can be injected as:
@PersistenceContext(unitName="HelloJPAPU")
EntityManager em;

Posted by Arun Gupta on February 05, 2009 at 07:35 AM PST #

To connect to MySQL I define a MySQL JDBC Ressource and call it jdbc/mysql_resource. I had to use this in persistence.xml ( had to define a non-jta-data-source called jdbc/mysql_resource as well as classes )

Posted by New Funny Pictures on March 08, 2009 at 07:28 AM PDT #

<strong>very good work</strong>

Posted by jj on March 19, 2009 at 10:38 AM PDT #

Hi Arun, great Post !!
I am a beginner and have just learn to use JPA.

I am using TOMCAT,MY SQL on eclipse.
After reading this post I am still confused how to use NY SQL instead of Oracle.
To be specific, what are the changes I have to do in persistance.XML and other ones ?

Thanx
Nivesh

Posted by Nivesh Somani on February 16, 2010 at 08:35 PM PST #

Nivesh,

This blog uses JavaDB. For any other database, you need to copy the appropriate JDBC driver file in domains/domain1/lib/ext directory and create the JDBC connection pool/resource accordingly. The instructions for MySQL/Oracle database are defined at:

http://blogs.sun.com/arungupta/entry/ttd_121_jdbc_resource_for

And then you can create PU as explained at:

http://blogs.sun.com/arungupta/entry/totd_122_creating_a_jpa

-Arun

Posted by Arun Gupta on February 17, 2010 at 01:36 AM PST #

Hi Arun,
I have a question.
I generally use Oracle Database with JPA, but now i had to change to MS SQL Server 2005.
What changes should i make so that i can use JPA with SQL Server.
Can you write a blog on using JPA with SQL Server? It'll be really helpful. Thanks.. :)

Posted by Sridhar on April 12, 2010 at 03:59 PM PDT #

MS SQL Server will require the corresponding JDBC driver and then connect using NetBeans. I don't have MS SQL Server installed on my machine so cant try/blog the steps. I'd suggest googling :-)

Posted by Arun Gupta on April 12, 2010 at 11:12 PM PDT #

when i run Junit for JPA i am getting java.lang.NullPointer Exception.how can i solve tat

Posted by vignesh on May 19, 2010 at 08:52 PM PDT #

Please send your question to users@glassfish.dev.java.net with details.

Posted by Arun Gupta on May 20, 2010 at 09:24 AM PDT #

i am using netbeans6.8 , i am new to JPA . i have connected Mysql using suitable driver.
i created entity java page( from new-> entity class from database ) and mapped table with java entity. when i try to do Junit for entity java. its showing java.lang.NullPointgerException.how can i solve tat error?
can u give me an example for performing Junit test for JPA unit in Netbeans 6.8

Posted by vignesh on May 20, 2010 at 06:49 PM PDT #

Vignesh,

Can you please provide the entire stack trace ? Where is the NPE coming from.

Posting your question to users@glassfish.dev.java.net or persistence@glassfish.dev.java.net will yield a better/quicker response.

Posted by Arun Gupta on May 21, 2010 at 03:33 AM PDT #

import java.util.List;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.UserTransaction;
import junit.framework.TestCase;

/\*\*
\*
\* @author vignesh
\*/
public class CategoryTest extends TestCase {
@PersistenceContext(unitName="WebApplication8PU")
private EntityManager em;
@Resource
private UserTransaction utx;

public CategoryTest(String testName) {
super(testName);
}
public void testlistallproducts()
{
try
{
List<Category> listProducts = em.createNamedQuery("Category.findAll").getResultList();
for (Category product : listProducts) {

System.out.println("name: " + product.getName());
System.out.println("Product: " + product.getDescription());
System.out.println("imageurlBig: " + product.getImageUrlBig());
System.out.println("imageurlsmall: " + product.getImageUrlSmall());
System.out.println("---------------------------------------");
}
}catch(Exception e)
{
System.out.print(e);
}
}
}
when i run this junit i got an error
Testsuite: server.CategoryTest
java.lang.NullPointerExceptionjunit.framework.TestListener: endTest(testlistallproducts)
Tests run: 14, Failures: 0, Errors: 0, Time elapsed: 0.189 sec

------------- Standard Output ---------------
java.lang.NullPointerException------------- ---------------- ---------------
test-single:
BUILD SUCCESSFUL (total time: 7 seconds)
And in the testresult
i got
java.lang.NullPointerException with 100% in test passed ..i dont know what is the error ? where WebApplication8PU is my Persistence Unit Name...
can u provide me an example for JPA junit test?

Posted by vignesh on May 23, 2010 at 09:14 PM PDT #

my stack trace value is

java.lang.NullPointerException
at server.CategoryTest.testlistallproducts(CategoryTest.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at junit.framework.TestCase.runTest(TestCase.java:164)
at junit.framework.TestCase.runBare(TestCase.java:130)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:120)
at junit.framework.TestSuite.runTest(TestSuite.java:230)
at junit.framework.TestSuite.run(TestSuite.java:225)
at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.run(JUnitTestRunner.java:515)
at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.launch(JUnitTestRunner.java:1031)
at org.apache.tools.ant.taskdefs.optional.junit.JUnitTestRunner.main(JUnitTestRunner.java:888)

Posted by vignesh on May 23, 2010 at 11:40 PM PDT #

Hi Guru,
i think this is the the No 1 lecture in all java developers world.
God give you more Strength to do more and more work for your friends.(like us)

Posted by Muhammad Sulaiman on September 16, 2010 at 05:14 AM PDT #

Post a Comment:
Comments are closed for this entry.
About

profile image
Arun Gupta is a technology enthusiast, a passionate runner, author, and a community guy who works for Oracle Corp.


Java EE 7 Samples

Stay Connected

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today