X

TOTD #93: Getting Started with Java EE 6 using NetBeans 6.8 M1 & GlassFish v3 - A simple Servlet 3.0 + JPA 2.0 app

Guest Author


href="http://www.netbeans.org/servlets/NewsItemView?newsItemID=1413">NetBeans
6.8 M1 introduces support for creating Java EE 6 applications
... cool!



This Tip style="font-weight: bold;">Of style="font-weight: bold;">The style="font-weight: bold;">Day (TOTD) shows how
to create a simple web application using JPA 2.0 and Servlet 3.0 and
deploy on GlassFish v3 href="http://download.java.net/glassfish/v3/promoted/">latest
promoted build ( href="http://download.java.net/glassfish/v3/promoted/glassfish-v3-preview-b58.zip">58
as of this writing). If you can work with the one week older build then
NetBeans 6.8 M1 comes pre-bundled with 57. The example below should
work fine on that as well.

  1. Create the database, table, and populate some data into it
    as shown below:

    style="text-align: left; background-color: rgb(204, 204, 255); width: 100%;"
    cellpadding="2" cellspacing="2">~/tools/glassfish/v3/58/glassfishv3/bin > style="font-weight: bold;">sudo mysql --user root

    Password:

    Welcome to the MySQL monitor.  Commands end with ; or \\g.

    Your MySQL connection id is 1592

    Server version: 5.1.30 MySQL Community Server (GPL)


    Type 'help;' or '\\h' for help. Type '\\c' to clear the buffer.


    mysql> create
    database states;


    Query OK, 1 row affected (0.02 sec)


    mysql> CREATE
    USER duke IDENTIFIED by 'glassfish';


    Query OK, 0 rows affected (0.00 sec)


    mysql> GRANT ALL
    on states.\* TO duke;


    Query OK, 0 rows affected (0.24 sec)


    mysql> use states; style="font-weight: bold;">Database changed


    mysql> CREATE
    TABLE STATES (

       
    ->      
    id INT,

       
    ->      
    abbrev VARCHAR(2),

       
    ->      
    name VARCHAR(50),

       
    ->      
    PRIMARY KEY (id)

       
    -> );


    Query OK, 0 rows affected (0.16 sec)


    mysql> INSERT
    INTO STATES VALUES (1, "AL", "Alabama");

    INSERT INTO
    STATES VALUES (2, "AK", "Alaska");



    . . .


    mysql> INSERT
    INTO STATES VALUES (49, "WI", "Wisconsin");


    Query OK, 1 row affected (0.00 sec)


    mysql> INSERT
    INTO STATES VALUES (50, "WY", "Wyoming");


    Query OK, 1 row affected (0.00 sec)

    The complete INSERT statement is available in href="http://blogs.sun.com/arungupta/entry/totd_38_creating_a_mysql">TOTD
    #38. Most of this step can be executed from within the IDE as
    well as explained in href="http://blogs.sun.com/arungupta/entry/totd_38_creating_a_mysql">TOTD
    #38.
  2. Download and unzip GlassFish v3 href="http://download.java.net/glassfish/v3/promoted/glassfish-v3-preview-b58.zip">build
    58. Copy the latest href="http://dev.mysql.com/downloads/connector/j/5.1.html">MySQL
    Connector/J
    jar in "domains/domain1/lib" directory of GlassFish and start the
    application server
    as:

    style="text-align: left; background-color: rgb(204, 204, 255); width: 100%;"
    cellpadding="2" cellspacing="2">~/tools/glassfish/v3/58/glassfishv3/bin > style="font-weight: bold;">asadmin start-domain
  3. Create JDBC connection pool and JNDI resource as shown
    below:

    style="text-align: left; background-color: rgb(204, 204, 255); width: 100%;"
    cellpadding="2" cellspacing="2">~/tools/glassfish/v3/58/glassfishv3/bin > style="font-weight: bold;">./asadmin
    create-jdbc-connection-pool --datasourceclassname
    com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource --restype
    javax.sql.DataSource --property
    "User=duke:Password=glassfish:URL=jdbc\\:mysql\\://localhost/states"
    jdbc/states


    Command create-jdbc-connection-pool executed successfully.

    ~/tools/glassfish/v3/58/glassfishv3/bin > style="font-weight: bold;">./asadmin ping-connection-pool
    jdbc/states


    Command ping-connection-pool executed successfully.

    ~/tools/glassfish/v3/58/glassfishv3/bin > style="font-weight: bold;">./asadmin create-jdbc-resource
    --connectionpoolid jdbc/states jdbc/jndi_states


    Command create-jdbc-resource executed successfully.
  4. Download href="http://bits.netbeans.org/netbeans/6.8/m1/">NetBeans
    6.8 M1 and install "All" version. Expand "Servers" node and
    add the recently installed GlassFish server.
  5. Create a new Web project and name it "HelloEclipseLink".
    Make sure to choose "GlassFish v3" as the server and "Java EE 6 Web" as
    the Java EE version as shown below:

    alt=""
    src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/fe780e8f18bfd4ef6d2204d3524c13f9/nb68m1_jpa_javaee6web.png">


    Take defaults elsewhere.
  6. Create the Persistence Unit
    1. Right-click on the newly created project and select
      "New", "Entity Classes from Database ...". Choose the earlier created
      data source "jdbc/jndi_states" as shown below:

      alt=""
      src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/32e65f1aeab82c95e042ca7660dba10b/nb68m1_jpa_datasource.png">
    2. Select "STATES" table in "Available Tables:" and click on
      "Add >" and then "Next >".
    3. Click on "Create Persistence Unit ...", take all the
      defaults and click on "Create". "EclipseLink" is the Reference
      Implementation for JPA 2.0 is the default choosen Persistence Provider
      as shown below:

      alt=""
      src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/df70a479f68eac80aeb313bd90a555b0/nb68m1_jpa_pu.png">
    4. Enter the package name as "server" and click on "Finish".
  7. Create a Servlet to retrieve and display all the
    information from the database
    1. Right click on the project, "New", "Servlet ...".
    2. Give the Servlet name "ShowStates" and package "server".
    3. Even
      though you can take all the defaults and click on "Finish" but instead
      click on "Next >" and the following screen is shown:

      alt=""
      src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/d3de69072c78dcba9af7722d57981778/nb68m1_jpa_servlet_deployment.png">


      Notice
      "Add information to deployment descriptor (web.xml)" checkbox. Servlet
      3.0 makes "web.xml" optional in most of the common cases by providing
      corresponding annotations and NetBeans 6.8 leverages that
      functionality. As a result, no "web.xml" will be bundled in our WAR
      file. Click on "Finish" now.


      The generated servlet code looks like:

      alt=""
      src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/969d831bb390b8de1bc113e6304c1cbf/nb68m1_jpa_servlet_annotations.png">


      Notice @WebServlet annotation, this makes "web.xml" optional. href="http://blogs.sun.com/arungupta/entry/totd_81_getting_started_with">TOTD
      #82 provide another example on how to use Servlet 3.0 with
      EJB 3.1.
    4. Inject the Persistence Unit as:

      style="text-align: left; background-color: rgb(204, 204, 255); width: 100%;"
      cellpadding="2" cellspacing="2">    @PersistenceUnit

          EntityManagerFactory emf;

      right above "processRequest" method.
    5. Change the "try" block of "processRequest" method to:

      style="text-align: left; background-color: rgb(204, 204, 255); width: 100%;"
      cellpadding="2" cellspacing="2">           
      List<States> list =
      emf.createEntityManager().createNamedQuery("States.findAll").getResultList();

                 
      out.println("<table border=\\"1\\">");

                 
      for (States state : list) {

                     
      out.println("<tr><td>" + state.getAbbrev() +

                             
      "</td><td>" + state.getName() +

                             
      "</td></tr>");

                 
      }

                 
      out.println("</table>");

      This uses a predefined query to retrieve all rows from the table and
      then display them in a simple formatted HTML table.
  8. Run the project
      1. Right click on the project, select "Properties" and
        change the "Relative URL" to "/ShowStates". This is the exact URL that
        you specified earlier.

        alt=""
        src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/66cde24136427f5e16222c638c7c0780/nb68m1_jpa_run.png">
      2. Right-click on the project and select "Run" to see the
        following output:

        alt=""
        src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/9fcea8e67206896135f1d58a5df52e0a/nb68m1_jpa_output.png">



    So we created a simple web application that uses Servlet 3.0, JPA 2.0,
    EclipseLink and deployed on GlassFish v3 using NetBeans 6.8 M1.
    NetBeans provides reasonable defaults making you a lazy programmer.
    Believe this is more evident when you start playing with Java EE
    support in other IDEs ;-)



    Finally, lets look at the structure of the generated WAR file:



    alt=""
    src="//cdn.app.compendium.com/uploads/user/e7c690e8-6ff9-102a-ac6d-e4aebca50425/f4a5b21d-66fa-4885-92bf-c4e81c06d916/Image/ddf935d9c34a9744f59da88150399e22/nb68m1_jpa_dir_structure.png">



    It's very clean - no "web.xml", only the relevant classes and
    "persistence.xml".



    Also refer to other href="http://blogs.sun.com/arungupta/tags/javaee6">Java EE 6
    blog entries. A future blog entry will show how to use JSF
    2.0 instead of Servlet for displaying the results.



    Please leave suggestions on other TOTD that
    you'd like to see.
    A complete archive of all the tips is available href="http://blogs.sun.com/arungupta/tags/totd">here.




    Technorati: totd
    glassfish
    v3 href="http://technorati.com/tags/mysql">mysql href="http://technorati.com/tags/javaee6">javaee6 href="http://technorati.com/tags/servlet3">servlet3
    jpa2 href="http://technorati.com/tags/netbeans">netbeans

    Join the discussion

    Comments ( 11 )
    • Johan Vos Thursday, August 13, 2009

      Thanks Arun, this is extremely useful. I was a bit stuck with the connection between servlet and JPA since I used "Persistence -> Use EntityManager" from NB.

      Your code (using EntityManagerFactory.createEntityManager()) did the job for me.

      Thanks a lot!

      - Johan


    • Arun Gupta's Blog Friday, August 14, 2009
      [Trackback] TOTD #93 showed how to get started with Java EE 6 using NetBeans 6.8 M1 and GlassFish v3 by building a simple Servlet 3.0 + JPA 2.0 web application. JPA 2.0 + Eclipselink was used for the database connectivity...
    • Arun Gupta's Blog Monday, August 17, 2009
      [Trackback] TOTD #93 showed how to get started with Java EE 6 using NetBeans 6.8 M1 and GlassFish v3 by building a simple Servlet 3.0 + JPA 2.0 web application. TOTD #94 built upon it by using Java Server Faces...
    • Pepo Thursday, August 27, 2009

      Hello.

      I'm trying to use a Telnet client (using the libraries from Apache Commons-Net) in a Stateless Bean but I have trouble doing and I think it is because these beans can not have this type of elements. My application must read requests from a database and as execute various commands such through an existing Telnet connection which I think is a good idea to open the connection in a Singleton Bean for another Stateless Bean (programmed with a schedule @Schedule) use this connection, so my question is. How do I make a Bean Stateless use the POJOs (in this case the Telnet connection) of a Singleton Bean?.

      Thank you very much for your help.


    • Arun Gupta Thursday, August 27, 2009

      Pepo, You've already asked the question at users@glassfish.dev.java.net and that is the right venue for such queries.


    • HJM Wednesday, April 7, 2010

      Arun -

      Enjoy site. I am a newbie and am pulling hair out (i.e., what's left). Environemnt working in is netbeans 6.8, Oracle 11g. Wrote servlet that leverages database Connection pool. Getting error

      SEVERE: javax.naming.NamingException: Lookup failed for 'java:/comp/env/jdbc/crcrms' in SerialContext [Root exception is javax.naming.NameNotFoundException: No object bound to name java:/comp/env/jdbc/crcrms]

      Not sure why?

      Please let me know if more information would help.

      Thanks.

      HJM


    • Arun Gupta Wednesday, April 7, 2010

      HJM,

      I assume your app is deployed on GlassFish :-)

      Did you try asadmin ping-connection-pool to see if the pool is setup correctly ?


    • Vance Monday, August 23, 2010

      I'm getting an error on step 7, specifically, on the 4th 'sub-step'. I add the following lines above the processRequest method declaration

      @PersistenceUnit

      EntityManagerFactory emf;

      and the error message I see when I hover above each line is

      cannot find symbol

      Any ideas as to how to resolve this?


    • Vance Monday, August 23, 2010

      Ok, turns out I just needed to import the necessary classes from the javax.persistence package to fix my earlier bug.

      But for some reason I'm unable to successfully deploy the created WAR file from within NetBeans 6.9. However, I was able to do so manually using the Admin application. Go figure.


    • deviprasad Thursday, September 30, 2010

      Hai arun, iam getting NullpointerException while injecting EAO class into my ejb using @Inject annotation please help me.

      Thanks in advance


    • Arun Gupta Tuesday, October 5, 2010

      deviprasad,

      GlassFish and NetBeans version ?


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