X

Hello JPA World!

Guest Author
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

Join the discussion

Comments ( 34 )
  • Kris Monday, July 2, 2007
    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.
  • Arun Monday, July 2, 2007
    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.
  • Kris Tuesday, July 3, 2007
    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
  • Arun Gupta's Blog Thursday, August 30, 2007
    [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...
  • suraj Saturday, November 10, 2007

    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


  • Arun Gupta Saturday, November 10, 2007

    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.


  • Arun Gupta's Blog Thursday, January 24, 2008
    [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...
  • Jessica Saturday, March 1, 2008

    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


  • Jessica Saturday, March 1, 2008

    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


  • Ben Saturday, March 8, 2008

    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.


  • Ben Saturday, March 8, 2008

    Restarted server and it works. Go figure.


  • Abishek Kumar Tuesday, March 18, 2008

    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.


  • Tony Monday, March 24, 2008

    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 )


  • Tony Monday, March 24, 2008

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


  • Joe Kingston Thursday, April 10, 2008

    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?


  • anonymus Wednesday, April 30, 2008

    [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)


  • anonymus Wednesday, April 30, 2008

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


  • laptop batteries Thursday, November 27, 2008

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


  • Harish Vembu Tuesday, January 6, 2009

    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


  • Arun Gupta Tuesday, January 6, 2009

    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.


  • Arun Gupta Thursday, February 5, 2009

    Instead of creating EntityManger as:

    EntityManagerFactory emf = Persistence.createEntityManagerFactory("HelloJPAPU");

    EntityManager em = emf.createEntityManager();

    it can be injected as:

    @PersistenceContext(unitName="HelloJPAPU")

    EntityManager em;


  • New Funny Pictures Sunday, March 8, 2009

    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 )


  • jj Thursday, March 19, 2009

    <strong>very good work</strong>


  • Nivesh Somani Wednesday, February 17, 2010

    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


  • Arun Gupta Wednesday, February 17, 2010

    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


  • Sridhar Monday, April 12, 2010

    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.. :)


  • Arun Gupta Tuesday, April 13, 2010

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


  • vignesh Thursday, May 20, 2010

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


  • Arun Gupta Thursday, May 20, 2010

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


  • vignesh Friday, May 21, 2010

    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


  • Arun Gupta Friday, May 21, 2010

    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.


  • vignesh Monday, May 24, 2010

    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?


  • vignesh Monday, May 24, 2010

    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)


  • Muhammad Sulaiman Thursday, September 16, 2010

    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)


Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.