JPA Tutorial



Table of Contents

  1. Introduction
  2. Suggested Audience
  3. System Requirements
  4. Getting Started
  5. Reverse Engineering
  6. Writing an Application
  7. Conclusion
  8. FAQ
  9. Resources
  10. Feedback

1. Introduction

Welcome to the MyEclipse JPA tutorial. In this tutorial we are going to take a look at some of the new JPA-based features in the MyEclipse 5.5 release and beyond. The project developed in this tutorial is available in ZIP format in our Resources section below.

JPA is the new Hibernate-like persistence specification that has become part of the Java EE 5 spec itself. JPA uses Java 5 annotations to control how plain Java classes (POJOs) get mapped to database tables. The MyEclipse tooling for JPA offers powerful generation and automation in the form of mapping existing DB tables directly to generated POJOs that are ready to be used against that database. MyEclipse also offers additional features for JPA in the Java source editor with reference to the annotations used to annotate the entities. MyEclipse will provide validation and autocomplete against the DB resources that the POJOs are referencing. For more general overview of JPA features offered in MyEclipse see the MyEclipse JPA Overview document.

2. Suggested Audience

This tutorial is intended for developers who are somewhat familiar with MyEclipse or Eclipse so you recognize navigation within the IDE, and understand some of the more common views like the debugger. It is also encouraged that the reader understand the basic idea of how JPA and entity mapping works along with annotations.

To learn more information about the topics presented in this tutorial please have a look at the links in our Resources section. To get a better feel for MyEclipse and learning more about it, please check out our product Documentation for more material.

3. System Requirements

This tutorial was created with MyEclipse 6.0. If you are using another version of MyEclipse, most of these screens and instructions should still be very similar.

If you are using a newer version of MyEclipse and notice portions of this tutorial looking different than the screens you are seeing, please let us know and we will make sure to resolve any inconsistencies.

4. Getting Started

Getting started with JPA in MyEclipse starts with two things:

  1. Having a project with JPA Capabilities added to it
  2. Using the DB Explorer to select table(s) to reverse-engineer using JPA

In MyEclipse you can add JPA Capabilities to many different kinds of projects. The most common are adding those capabilities to a Java Projects or Web Projects. In this tutorial we are going to use a simple Java Project to see how JPA works.

Setting up Your Project

First create your new project:

Now that your project is created, the next step is to create a DB Connection that we wish to use with this project. We cannot add JPA Capabilities until we have setup that connection because selecting the connection we wish to associate this project with is part of the JPA Capabilities wizard.

Setting up DB Connection

One of the new features since MyEclipse 5.5 is that it ships a preconfigured DB Connection pointed at an embedded install of the Apache Derby DBMS. Developers can immediately use this connection without needing to setup their own DBMS or connection.

To set up a DB connection first switch to the Database Explorer Perspective:

... and select the MyEclipse Derby connection, and click Open Connection before you start using it. This will automatically start the embedded MyEclipse Derby server and you'll have an instant access to all the tables in the database:

When you first connect to the Derby DB, MyEclipse ships a few sample schemas namely CLASSICCARS and MYBLOG :

The table we are going to work with is the PRODUCTLINE table. It contains a lot of sample data that you can view by right-clicking on the table and going to Edit Data:

Adding JPA Capabilities

Now that our DB Connection is setup and project is ready we need to add JPA Capabilities to our project in order to enable it to use tables and information from this DB Connection.

First, switch back to the MyEclipse Perspective, then right-click on the project and go down to the MyEclipse sub menu. From there, select Add JPA Capabilities...:

All the defaults on the first page of the JPA wizard are fine:

On the second page of the wizard we need to specify a name for our persistence unit. Any friendly name will work, we suggest using some variation of the project name for ease. Then we must specify the DB Connection and DB Schema to relate this project to. When you are done, click Finish:

Now our project has fully configured JPA Capabilities added to it, which include JPA configuration information, DB Connection information and all necessary JDBC and JPA libraries added to the project's build path. If this project were a Web Project, all the build-path additions would be prepared for deployment when the project was deployed to an app server and ran.

One last step is to create a new Java Package to reverse-engineer our entities into:

Then create a new package to place the classes in:

5. Reverse Engineering

Now that our project is setup, we are ready to reverse-engineer our PRODUCTLINE table into the project and start using the entities that are generated.

Right click on the JPA enabled project and select MyEclipse>Generate Entities from the context menu, as shown in the figure below:

In the reverse-engineering dialog that comes up, select the tables that you would want to reverse-engineer and hit Next. As an example we'll add the PRODUCTLINE table from the available tables list.

In the dialog that comes up next, you will want to fill out the following fields:

  • Java source folder: The folder in your project where the files will be generated
  • Java package: The package, that we created above, to place the generated classes
  • Entity Bean: Tell MyEclipse to generate plain Java classes that are correctly annotated to be used as JPA entities
    • Create abstract class: If you wish to customize the generated classes without fear of overwriting your changes each time, MyEclipse can generate base abstract classes as well as concrete subclasses that you can customize and use. Each time you reverse-engineer, MyEclipse will only overwrite the abstract base class, maintaining your changes in the concrete subclass.
    • Update persistence.xml: Similar to Hibernate, you can list all the JPA entities you will be using in the JPA configuration file.
  • Java Data Access Objects: Tell MyEclipse to generate DAO utility classes for you that allow you to save/find/update/delete the entities from the database right away. This code wraps the JPA entity manager and makes using the entities and the DB very easy.
    • Generate Precise findBy Methods: Tells MyEclipse to generate findByXXX methods where XXX pertains to each property on the entities that are reversed. This allows easy access to entities from the DB using any property as a means of finding them.

When we are done filling out the dialog, we can hit finish to reverse-engineer the table:

After reverse-engineering is done, we can go to the Persistence Perspective to use some of the persistence and datasource tools to analyze data in our DB and project. For the purpose of this tutorial we are going to flip back to the MyEclipse Perspective and take a look at the resources that MyEclipse generated for us:

Looking at them one at a time, we have:

  • Productline: This class is the JPA Entity (POJO) that represents the DB table PRODUCTLINE. This POJO has all the fields of the PRODUCTLINE table and represents one row in that DB.
  • ProductlineDAO: This class wraps the EntityManagerHelper to give us easy-to-use methods specifically for adding/finding/updating and deleting Productlines from the DB.
  • EntityManagerHelper: When using straight JPA, developers need to make use of the EntityManager class. This generated helper class tries to make using the EntityManager a much easier process by providing static methods to access the manager as well as the most common operations readily available to call.

6. Writing an Application

Now that MyEclipse has generate all this code for us, we can quickly focus on writing our "Business Logic", or more specifically, "the code that actually does stuff". In this tutorial we are going to keep things simple and write a single Java class, with a main method that inserts a Productline into the database, retrieves it, updates it and then deletes it. From this code you should be able to quickly see how easy it becomes actually using the JPA entities in your own applications without needing to write JDBC code or any other persistence code.

First, let's create our new Java class:

When the new class dialog pops up, be sure to give the class a name and tell the wizard to generate a main method:

After our new class and main method are generated, we need to write code that will successfully manipulate instances of Productline.

NOTE: The following code looks long and complex, but that's only because we are trying to show 4 different examples in one block of code. If you look at each operation (save, load, update, delete) none of them consist of more than a few lines of code.

That code is going to look like the following:

/* 1. Create a reference to our ID */
String productLineID = "Men's Shoes";

/* 2. Create a new Productline instance */
Productline newProductline = new Productline(
productLineID,
"Shoes for men.",
"Men's Shoes", null);

/* 3. Create a DAO instance to use */
ProductlineDAO dao = new ProductlineDAO();

/* 4. Store our new product line in the DB */
EntityManagerHelper.beginTransaction();
dao.save(newProductline);
EntityManagerHelper.commit();

/* 5. Now retrieve the new product line, using the ID we created */
Productline loadedProductline = dao.findById(productLineID);

/* 6. Print out the product line information */
System.out.println("*NEW* Product Line [productLine="
+ loadedProductline.getProductline() + ", textDescription="
+ loadedProductline.getTextdescription() + ", image="
+ loadedProductline.getImage() + "]");

/*
* 7. Now let's change same value on the product line, and save the
* change
*/

loadedProductline.setTextdescription("Product line for men's shoes.");

EntityManagerHelper.beginTransaction();
dao.save(loadedProductline);
EntityManagerHelper.commit();

/*
* 8. Now let's load the product line from the DB again, and make sure
* it text description changed
*/

Productline secondLoadedProductline = dao.findById(productLineID);

System.out.println("*REVISED* Product Line ["
+ "productLine=" + secondLoadedProductline.getProductline()
+ ", textDescription=" + secondLoadedProductline.getTextdescription()
+ ", image=" + secondLoadedProductline.getImage() + "]");

/* 9. Now let's delete the product line from the DB */
EntityManagerHelper.beginTransaction();
dao.delete(secondLoadedProductline);
EntityManagerHelper.commit();

/*
* 10. To confirm the deletion, try and load it again and make sure it
* fails
*/

Productline deletedProductline = dao.findById(productLineID);

/*
* We use a simple inlined IF clause to test for null and print
* SUCCESSFUL/FAILED
*/

System.out.println("Productline deletion: "
+ (deletedProductline == null ? "SUCCESSFUL" : "FAILED"));

Main class that uses JPA

NOTE: The code above in green are the markers for the beginning and the end of each transaction. It is a good idea to wrap segments of code that change the database with transactions, so if the operation fails (e.g. DB crashes) then all the changes that tried to occur in the transaction are rolled back to their original values instead of only half of the work getting done.

The code above may look daunting, but that's only because it's doing a lot of simple things back-to-back. If, for example, you were only interested in storing a new item in the database, you'd just have the code from Steps 1-3 in your program, which amounts (minus comments) to 3 lines of code. Not too shabby. Let's break each numbered section down now and look at what this code does:

  1. The PRODUCTLINE table uses the name of the product line as the primary key. To make this tutorial easier to follow, we simply define our product line name in a String and reuse it throughout the code (to create and store the product line, then to retrieve it twice). You could just as easily retyped "Men's Shoes" multiple times, but we thought this made the tutorial easier to follow.
  2. Here we are creating the new instance of the Productline POJO that was generated by MyEclipse and will be inserted into the DB. For the purpose of this tutorial the values are not important, so we just used some example info in there.
  3. Here we create an instance of the DAO to use. We need the DAO to do the actual DB access. This was generated by MyEclipse as well.
  4. Here we tell the DAO to actually store our new Productline in the DB. Because we are going to write something to the DB, we wrap our save call here in a transaction.
  5. In order to make sure that our Productline was stored correctly, using the ID we defined in Step #1 we ask the DAO to get our Productline and we assign the result to a brand new object, just to make absolutely sure that what is loaded, is from the DB. (We could have assigned the value back to newProductline, but for the purpose of the tutorial we wanted to be very obvious where objects are coming from and that the loaded instance hadn't existed before in our code accidentally).
  6. Here we print out the values from the loaded entity to make sure it's what we just stored in the DB.
  7. Here we change a value on the POJO we just loaded, to show how updating records work. And then we commit that change back to the DB using our DAO. Again this operation is wrapped in a transaction to make sure that our change to the DB is made safely.
  8. Just like in Step #5, here we are reloading the record from the DB, using it's ID we defined in Step #1 to make sure the update operation worked. We then print out the POJO values to make sure the new description did get saved to the DB.
  9. Here we are showing how deleting a record from the DB works. And again, because this requires a change to the DB, we wrap this code in a transaction as well.
  10. Similar to our Step #8 and Step #5, to prove that the delete worked, we try and load the entity from the DB using the ID we gave it. This operation should fail because we already erased the Productline. After we get the result from the DAO, we print out a statement with an embedded IF clause to make sure the result was null.

The output from running this looks like this:

The red text are default log messages from the generated DAO and EntityHelper classes in MyEclipse. The black text are the System.out.println text that we put in our code to track the progress through our code. As you can see the first print out from Step #6 and the updated print out from Step #8 all worked as expected. Also our deletion was successful as well since there was no Productline returned from our query after we erased it.

7. Conclusion

We have reached the end of our MyEclipse JPA tutorial. In this tutorial we tried to show not only the strengths of JPA as a persistence technology, but also of how much code MyEclipse will generate for you, allowing you to start coding your application immediately.

If you have any suggestions for us to help make it more informative, please let us know.

Below we would like to provide you with some more information pertaining to the topic covered in this tutorial. We offer the FAQ section for quick references to common questions and the Resources section with links to other helpful resources online that you may want to become familiar. We realize we can't cover every question you may have in one tutorial, but between this tutorial contents and our additional learning resources we hope you are far on your way to feeling comfortable with the technology.

8. Resources

In this section we want to provide you with additional links to resources that supplement the topics covered in this tutorial. While this is not an exhaustive list, we do make an effort to point to the more popular links that should provide you with diverse, high-quality information.



Common Reference

Misc Reference


0 comments: