TOTD #99: Creating a Java EE 6 application using MySQL, JPA 2.0 and Servlet 3.0 with GlassFish Tools Bundle for Eclipse

TOTD #97 showed how to install GlassFish Tools Bundle for Eclipse 1.1. Basically there are two options - either install Eclipse 3.4.2 with WTP and pre-bundled/configured with GlassFish v2/v3, MySQL JDBC driver and other features. Or if you are using Eclipse 3.5, then you can install the plug-in separately and get most of the functionality.

TOTD #98 showed how to create a simple Metro/JAX-WS compliant Web service using that bundle and deploy on GlassFish.

This Tip Of The Day (TOTD) shows how to create a simple Java EE 6 application that reads data from a MySQL database using JPA 2.0 and Servlet 3.0 and display the results. A more formal support of Java EE 6/Servlet 3.0 is coming but in the meanwhile the approach mentioned below will work.

Lets get started!

  1. Configure database connection - The key point to notice here is that the MySQL Connector/J driver is already built into the tool so there is no need to configure it explicitly.
    1. From "Window", "Show Perspective", change to the database perspective as shown below:

    2. In the "Data Source Explorer", right-click and click on "Database Connections" and select "New ...":

    3. Search for "mysql" and type the database name as "sakila":



      This blog uses MySQL sample database sakila. So please download and install the sample database before proceeding further.
    4. Click on "Next >" and specify the database configuration:



      Notice the "Drivers" indicate that the JDBC driver is pre-bundled so there is no extra configuration required. If you are using a stand-alone Eclipse bunde and installing the plugin separately, then you need to configure the MySQL JDBC driver explictily.

      The URL indicates the application is connecting to the sakila database. Click on "Test Connection" to test connection with the database and see the output as:



      and click on "Finish" to complete. The expanded database in the explorer looks like:



      The expanded view shows all the tables in the database.
  2. Create the Web project & configure JPA
    1. Switch to JavaEE perspective by clicking "Window", "Choose Perspective", "Other ..." and choosing "Java EE".
    2. Create a new dynamic web project with the following settings:



      Only the project name needs to be specified and everything else is default. Notice the target runtime indicates that this is a Java EE 6 application. Click on "Finish".
    3. Right-click on the project, search for "facets" and enable "Java Persistence" as shown below:

    4. Click on "Further configuration available ..." and modify the facet as shown below:



      Make sure to disable "orm.xml" since we are generating a standard Java EE 6 web application. Choose "sakila" as the database. Click on "OK" and again on "OK" to complete the dialog.
  3. Generate the JPA entities
    1. Right-click on the project, select "JPA Tools", "Generate Entities" as shown:

    2. Choose the schema "sakila":



      and click on "Next >". If no values are shown in the schema drop-down, then click on "Reconnect ...".
    3. Specify a package name for the generated entities as "model" and select "film" and "language" table:



      and click on "Finish". The "film" and "language" table are related so it would be nice if all the related tables can be identified and picked accordingly.

      Anyway this generates "model.Film" and "model.Language" classes and "persistence.xml" as shown below:



      Also notice that "web.xml" and "sun-web.xml" have been explicitly removed since they are not required by a Java EE 6 application.
    4. "model.Film" class needs to modified slightly because one of the columns is mapped to "Object" which is not a Serializable obect. So change the type of "specialFeatures" from Object to String and also change the corresponding getters/setters accordingly. The error message clearly conveyed during the initial deployment and so could be fixed. But it would be nice to generate the classes that will work out-of-the-box.
  4. Create a Servlet client to retrieve/display data from the database
    1. Right-click on the project, select "New", "Class" and specify the values as:



      and click on "Finish". This class will be our Servlet client.
    2. Change the class such that it looks like:
      @WebServlet(urlPatterns="/ServletClient")
      public class ServletClient extends HttpServlet {
        @PersistenceUnit
        EntityManagerFactory factory;
      
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
               throws ServletException, IOException {
          ServletOutputStream out = resp.getOutputStream();
          List list = factory.createEntityManager().createQuery("select f from Film f where f.title like 'GL%';").getResultList();
          out.println("<html><table>");
          for (Object film : list) {
            out.print("<tr><td>" + ((Film)film).getTitle() + "</tr></td>");
          }
          out.println("</table></html>");
        }
      }
      

      and the imports as:
      import java.io.IOException;
      import java.util.List;
      
      import javax.persistence.EntityManagerFactory;
      import javax.persistence.PersistenceUnit;
      import javax.servlet.ServletException;
      import javax.servlet.ServletOutputStream;
      import javax.servlet.annotation.WebServlet;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      
      import model.Film;
      
      
      Basically, this is a Servlet 3.0 specification compliant Servlet that uses @WebServlet annotation. It uses @PersistenceUnit to inject the generated JPA Persistence Unit which is then used to query the database. The database query return all the movies whose title start with "GL" and the response is displayed in an HTML formatted table.
    3. Right-click on the project and select "Run As", "Run on Server" and select GlassFish v3 latest promoted build (this blog used build 61) as:



      and click on "Finish". The output at "http://localhost:8080/HelloJPA/ServletClient" looks like:

Simple, easy and clean!

How are you using Eclipse and GlassFish - the consolidated bundle or standalone Eclipse + GlassFish plugin ?

Download GlassFish Tools Bundle for Eclipse now.

Please send your questions and comments to users@glassfishplugins.dev.java.net.

Please leave suggestions on other TOTD that you’d like to see. A complete archive of all the tips is available here.

Technorati: glassfish eclipse mysql jpa database

Comments:

Hi,

I can't generate entities from tables.

In your TOTD #99 "TOTD #99: Creating a Java EE 6 application using MySQL, JPA 2.0 and Servlet 3.0 with GlassFish Tools Bundle for Eclipse" you show how to generate entities from tables. I followed your steps until step 3 (Generate the JPA entities). But when i select "JPA Tools" and "Generate Entities", no window appears.

I don't no, if my configuration is wrong or if this is bug in galileo eclipse?
I read in eclipse community forums it's possibly a bug in galileo eclipse (topic in eclipse community forums: Generate Entities from Tables not working).

I use:
- Eclipse Galileo Version: 3.5.2.R35x_v20100119-7Q7bARBPWUHM_CSjz-8bF1f7_n8rLSyWHoiKoyxBQSGT4
Build id: M20100211-1343, 64bit.

- mysql Version 5.1.45-community

- Java Version 1.6.0-19, 64bit

- Dali 2.2.2 ("Dali Java Persistence Tools" and "Dali Java Persistence Tools - EclipseLink Support (Optional)")

Posted by Jean Guissa on April 18, 2010 at 09:54 AM PDT #

Jean,

I've not tried stand alone Eclipse and so can't comment upon that. I'd recommending posting in the Eclipse forums for that.

Posted by Arun Gupta on April 19, 2010 at 08:20 AM PDT #

I just tried this with Eclipse 2.0.1 and had no problems with this. Make sure you have the latest updates.

Posted by Lance Andersen on April 22, 2010 at 05:28 AM PDT #

Hi Arun Gupta, Pls help me out.. am getting Ping Failed!

Posted by guest on August 13, 2011 at 05:43 AM PDT #

Have you looked at the GlassFish server log to look at the error ?

Posted by Arun on September 05, 2011 at 06:35 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 2015
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