MyEclipse Logo
 

MyEclipse JPA and Spring Tutorial

Table of Contents

download the latest MyEclipse version

help and support
 

1. Introduction

Welcome to the MyEclipse JPA and Spring tutorial. In this tutorial we are going to take a look at some of the JPA-Spring based features available in MyEclipse. It is highly encouraged that you read the MyEclipse JPA Tutorial first, as this tutorial is built on top of the first one, adding JPA-Spring support to a very similar project and working with the same examples. The project developed in this tutorial is available in ZIP format in our Resources section below.

Because the MyEclipse JPA Tutorial covers all the basics of setting up a JPA project, this tutorial will go over those details much faster and in less detail. The detail and time will be spent explaining the JPA-Spring integration in MyEclipse and how to utilize that functionality.


 

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 Spring 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. However, if you 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 and Spring in MyEclipse begins with two things:

  1. Having a project with JPA Capabilities added to it
  2. Then adding Spring Capabilities to that project
  3. Reverse-engineering your database into your project using JPA entities and Spring DAOs

NOTE: You can also add the Capabilities in reverse order (Spring first, then JPA) and get the same functionality.

In MyEclipse you can add JPA and Spring 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 these technologies work.

Setting up Your Project

We already know how to setup a new Java Project and add JPA Capabilities to it as was outlined in the MyEclipse JPA Tutorial, we want to do the same thing again. In this case we name the project SampleJPASpringProject.

After we are done we need to add Spring Capabilities to the project. First you right-click on the root of the project, and go down to MyEclipse then Add Spring Capabilities...:

Figure 1. Adding Spring Capabilities

On the first screen of the Spring Capabilities wizard, you'll notice the new option Add Spring-JPA Support. This checkbox tells MyEclipse to generate sources in this JPA project that integrate Spring and JPA together. By default, because we are adding Spring to a JPA project, this will be checked:

Figure 2. Adding Spring-JPA Capabilities
Figure 3. Setting up Bean Configuration

The last page allows you to specify the names of your entity manager factory bean and transaction manager bean. You also have the option of telling MyEclipse to add annotation-based transaction support; more specifically, support for using @Transactional Spring annotation):

Figure 4. Turning on Annotation Support

Note: Annotation based transaction support is covered in the Spring Container-Managed Transactions section.

Now that our project has JPA and Spring Capabilities added to it, we can pop open the applicationContext.xml Spring bean configuration file and see how our project is configured now:

Figure 5. Spring Configuration View

You can see from the visual layout of the Spring bean configuration file how the different beans are configured. The transactionManager uses the entitytManagerFactory which in turn uses the JPA persistence unit (that was created when we added JPA capabilities).


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.

To reverse-engineer we want to select the package we created to generate our entities into, right-click on it, go down to MyEclipse then select Generate Entities & DAOs...:

Figure 6. Reverse Engineering
Figure 7. Select PRODUCTLINE Table

After selecting the table to reverse-engineer and hitting next you will be prompted to select how you want the entities and DAOs generated:

Figure 8. Generating Entities

When the reverse-engineering dialog comes up 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.
    • Generate Java interfaces: This tells MyEclipse to generate top-level DAO interfaces as well as concrete implementations (e.g. IProductlineDAO and ProductlineDAO)
    • DAO Type: Depending on the type of DAO generated, MyEclipse (besides generating the DAO implementation for you) can also update your Spring bean configuration file with the new DAO hooked to the existing entityManagerFactory for you.

When we are done filling out the dialog, we can hit finish to reverse-engineer the table. When the reverse-engineering is done, we can look at our project's Spring configuration again and see that it's been updated for us:

Figure 9. New Spring DAO

With the update Spring view we now see our ProductlineDAO included and dependent on the entityManagerFactory bean.


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 the previous MyEclipse JPA Tutorial we covered what each of the entity and DAO classes did as well as the basic outline of our main method that ran a simple scenario for us including:

  1. Create a new entity and insert it in the database
  2. Retrieve the entity
  3. Update the entity
  4. Delete the entity

In this tutorial we are going to keep things very similar, almost identical in fact, but we will show how to use Spring to get and use our DAO as well as manage transactions.

Our starting point for our demo is going to be the RunJPA.java class. Look at the main method in that class, we see:

/* 1. Initialize the transactionManager and DAO */
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
        "/applicationContext.xml");
txManager = ((JpaTransactionManager) ctx.getBean("transactionManager"));
dao = ProductlineDAO.getFromApplicationContext(ctx);


/* 2. Create a reference to our ID */
String productlineID = "Men Shoes";

/* 3. Save a new productline to the DB */
saveProductline(productlineID);

/* 4. Load the productline from DB to make sure it worked */
loadProductline(productlineID);

/* 5. Update the productline in the DB and check it */
updateProductline(productlineID);

/* 6. Delete the productline from the DB */
deleteProductline(productlineID);
Figure 10. Main method to run JPA-Spring Example

The section of the code marked in blue are the Spring calls where we retrieve our configured beans from our bean configuration. Notice that since we are managing the transactions manually, we also retrieve the transactionManager from the bean configuration as well.

The remaining items, #2 - #6, simple make calls to each of our methods that "do something". We will look at each one and see what it does and how it does it.


6.1 Saving an Entity

The first interesting method we run into is saveProductline. The purpose of this method is to create a new entity and store it in the DB:

/* 1. Create a new Productline instance */
Productline newProductline = new Productline(productlineID,
        "Shoes for men.", "<strong>Men Shoes</strong>", null);

/* 2. Store our new product line in the DB */
TransactionStatus status = txManager
        .getTransaction(new DefaultTransactionDefinition());
dao.save(newProductline);
txManager.commit(status);
Figure 11. saveProductLine implementation
  1. We create our new Productline instance with some basic values.
  2. Using the transactionManager, we begin a transaction right before we try and save the entity in the DB. After we are done saving the entity we commit the transaction.

The purpose of managing the transaction ourselves is because as the developers, we know the scope of the "save" operation. Depending on how your application is written, some operations may have a scope that encompasses many DB modifications, wrapping those all in a single transaction is important in case half way through the job it fails. You wouldn't want to leave your data in a state where some of it is correct and some of it is stale.


6.2 Retrieving an Entity

The next method we look at will retrieve our entity from our DB using the ID we assigned it, and display all it's values; confirming that our save operation worked:

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

/* 2. Print out the product line information */
System.out.println("*NEW* Product Line [productLine="
        + loadedProductline.getProductline() + ", textDescription="
        + loadedProductline.getTextdescription() + "]");
Figure 12. loadProductline implementation

Notice that in this code we do not use transactions. The reason for this is that this code only performs a read operation and not a write operation. So even if the operation failed, none of the data in the DB would be effected. So there is no need to protect the operation using a transaction.


6.3 Updating an Entity

Now the next section of code might look longer, but that's only because we are printing out the new values and confirming that the record got updated in the DB:

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

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

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

TransactionStatus status = txManager
        .getTransaction(new DefaultTransactionDefinition());
dao.update(loadedProductline);
txManager.commit(status);

/*
 * 3. 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() + "]");
Figure 13. updateProductline implementation

Notice that we wrap the update call with a transaction, this is because it has to write something to the database and we need to protect it from failure.

In section #3 above we are loading the productline from the database right after we updated it, and printing out the values we get back from the database to confirm that it's updated.


6.4 Deleting an Entity

Deleting an entity is almost identical to how we saved and updated the entity. We wrap our work in a transaction and then tell the DAO to do the work for us:

/* 1. Now retrieve the new product line, using the ID we created */
TransactionStatus status = txManager
        .getTransaction(new DefaultTransactionDefinition());
Productline loadedProductline = dao.findById(productlineID);

/* 2. Now let's delete the product line from the DB */
dao.delete(loadedProductline);
txManager.commit(status);

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

Productline deletedProductline = dao.findById(productlineID);

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

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

Similar to our updateProductline implementation above, you'll notice that we use the transaction to wrap the delete call and then attempt to load the entity from the DB and confirm that the operation should fail.

NOTE: The reason the transaction has to wrap both the findById and delete method calls is because objects managed by JPA must be part of the same transaction. So in order for us to erase the object we load, it has to be in the same transaction that we loaded it and tried to erase it.


6.5 Running the Program

The output from running this looks like this:

Figure 15. Output

The red text are default log messages that can be ignored (You can setup a custom log4j.properties file if you wish to control logging).

Then below the log warnings we see 2 messages from TopLink (our JPA implementation libraries) and then we see 3 more messages, all from our implementation.

Our first message prints out the new productline information that was added, the second one updates it and prints the new information and the last one deletes it from the DB and prints the confirmation message.


7. Advanced Topics


7.1 Spring Container-Managed Transactions

In addition to the user managed transactions described in the previous section, Spring also supports container-managed transactions via the @Transactional attribute. For container-managed transaction support, you must enable it during capability addition:

Figure 16. Turning on support for the @Transactional annotation

Enabling this adds the following element to your bean configuration file. We also add a JPAServiceBean which we will use to delete an entity using container-managed transactions.

Figure 17. Annotation driven configuration element

The JPAServiceBean implementation is shown below, note the @Transactional annotation on the deleteProductLine method and the absence of any user-managed transaction statements.

	
public class JPAServiceBean {

	private IProductlineDAO dao;
	@Transactional
	public void deleteProductLine(String productlineID) {
		/* 1. Now retrieve the new product line, using the ID we created */
		Productline loadedProductline = dao.findById(productlineID);
		/* 2. Now let's delete the product line from the DB */
		dao.delete(loadedProductline);
		/*
		 * 3. To confirm the deletion, try and load it again and make sure it
		 * fails
		 */
		Productline deletedProductline = dao.findById(productlineID);
		/*
		 * 4. We use a simple inline IF clause to test for null and print
		 * SUCCESSFUL/FAILED
		 */
		System.out.println("Productline deletion: "
				+ (deletedProductline == null ? "SUCCESSFUL" : "FAILED"));
	}
	
	public void setProductLineDAO(IProductlineDAO dao) {
		this.dao = dao;
	}
	
}
Figure 18. @Transactional deleteProductline implementation

Obtain an instance of JPAServiceBean from the application context and use it as follows:

JPAServiceBean bean = (JPAServiceBean) ctx.getBean("JPAServiceBean");
bean.deleteProductLine(productlineID);
Figure 19. Using JPAServiceBean


8. Conclusion

We have reached the end of our MyEclipse JPA Spring tutorial. In this tutorial we tried to show not only the strengths of JPA as a persistence technology, but how powerful the combination of JPA and Spring together can be for developing large, robust applications. It is also important to note that we wrote very little code while MyEclipse generated the vast majority of it for us.

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.


9. 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.

Tutorial Material



10. Feedback

We would like to hear from you! If you liked this tutorial, has some suggestions or even some corrections for us please let us know. We track all user feedback about our learning material in our Documentation Forum.  Please be sure to let us know which piece of MyEclipse material you are commenting on so we can quickly pinpoint any issues that arise.