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!
-
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.
- From "Window", "Show Perspective", change to the database perspective as shown below:

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

- 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.
- 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.
- From "Window", "Show Perspective", change to the database perspective as shown below:
-
Create the Web project & configure JPA
- Switch to JavaEE perspective by clicking "Window", "Choose Perspective", "Other …" and choosing "Java EE".
- 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".
- Right-click on the project, search for "facets" and enable "Java Persistence" as shown below:

- 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.
-
Generate the JPA entities
- Right-click on the project, select "JPA Tools", "Generate Entities" as shown:

- Choose the schema "sakila":

and click on "Next >". If no values are shown in the schema drop-down, then click on "Reconnect …".
- 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.
- "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.
- Right-click on the project, select "JPA Tools", "Generate Entities" as shown:
-
Create a Servlet client to retrieve/display data from the database
- Right-click on the project, select "New", "Class" and specify the values as:

and click on "Finish". This class will be our Servlet client.
-
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.
- 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:

- Right-click on the project, select "New", "Class" and specify the values as:
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
Related posts:- TOTD #102: Java EE 6 (Servlet 3.0 and EJB 3.1) wizards in Eclipse
- TOTD #94: A simple Java Server Faces 2.0 + JPA 2.0 application – Getting Started with Java EE 6 using NetBeans 6.8 M1 & GlassFish v3
- TOTD #93: Getting Started with Java EE 6 using NetBeans 6.8 M1 & GlassFish v3 – A simple Servlet 3.0 + JPA 2.0 app
- LOTD #20: How to create a JPA application using GlassFish Tools Bundle for Eclipse ?
- TOTD #98: Create a Metro JAX-WS Web service using GlassFish Tools Bundle for Eclipse
[...] Read more from the original source: TOTD #99: Creating a Java EE 6 application using MySQL, JPA 2.0 … [...]
Pingback by TOTD #99: Creating a Java EE 6 application using MySQL, JPA 2.0 … | Webmaster Tools — August 30, 2009 @ 6:41 pm
I tried to run the same example using Netbeans with Postgresql (using Pagila port of the Sakila), i got the following error when deploying the application. It complains about Film entity.
Exception:
SEVERE: Exception while invoking class org.glassfish.persistence.jpa.JPADeployer prepare method
javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services – 2.0.0.v20090713-r4647): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [jpaPU] failed.
Internal Exception: Exception [EclipseLink-7164] (Eclipse Persistence Services – 2.0.0.v20090713-r4647): org.eclipse.persistence.exceptions.ValidationException
Exception Description: The type [class java.lang.Object] for the attribute [rating] on the entity class [class model.Film] is not a valid type for a lob mapping. For a lob of type BLOB, the attribute must be defined as a java.sql.Blob, byte[], Byte[] or a Serializable type. For a lob of type CLOB, the attribute must be defined as a java.sql.Clob, char[], Character[] or String type.
Any tips would be very helpful. Thank you.
Comment by Ramkumar — September 10, 2009 @ 6:42 pm
Not familar with Pagila port of the Sakila or NetBeans with Postgresql. Please try posting your question to nbusers@netbeans.org.
Comment by arungupta — September 11, 2009 @ 9:59 am
[...] TOTD #99: Creating a Java EE 6 application using MySQL, JPA 2.0 and Servlet 3.0 with GlassFish Tools… [...]
Pingback by TOTD #102: Java EE 6 (Servlet 3.0 and EJB 3.1) wizards in Eclipse - Technology — September 14, 2009 @ 4:00 am
I tried to run this example exactly as you said here and got the following error :
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services – 2.0.0.v20090821-r4934): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: Error in allocating a connection. Cause: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused: connect.
Error Code: 0
in the DataSourceExplorer i have a connection with the database on port 3306, the Test Connection worked perfectly. what am i doing wrong ?
Comment by Razvan — November 8, 2009 @ 11:03 am
Razvan, Can you please your question to users@glassfishplugins.dev.java.net with complete details ? What version of GlassFish, Eclipse plug-in or co-bundle ?
Comment by arungupta — November 9, 2009 @ 9:24 am
I just did this, hope you can help.
Thanks.
Comment by Razvan — November 9, 2009 @ 1:10 pm
Ok, I still didnt get an answer from you guys, but i tried some more.
Still doesn’t work with eclipse 3.5, Glassfish 3 server build b62 and glassfish plugin v1.0.39 (the same error as in the last post).
I used the GlassFish Tools Bundle for Eclipse 1.1 (as it is, no updates or anything) to try to run this but in this bundle there is GlassFish v3 Prelude (build b28d) that doesn’t support EJB 3.0 so we cant use JPA 2.0 with the @Entity Annotations and so on. (I also tried to update the server with the Update Tool, installing glassfish ejb (it didn’t work), then i just applied all the updates i could there, but then i couldn’t create a runtime with it).
Comment by Razvan — November 11, 2009 @ 12:56 am
it always amazes me how all these tutorials never reflect “real world code”. If you implemented your servlet as shown, you’d get a swift kick in the ass and out the door with your pink slip. I wish these tutorial guys would spend an extra 10 minutes and just use a proper pattern that reflects the real world. We would all end up with less buggy sites out there. And I realize the examples are just “to show” how jpa works, but it’s demonstrating a horrible use of a servlet. It wouldn’t have taken much more effort to decouple the presentation, content and db access in this example. If you’re going to show something, show it correctly, or don’t show it at all. Bad examples are leading to unmaintainable code.
Comment by billy vandory — May 16, 2010 @ 6:14 pm