|
||||||||||||
Table of Contents |
||||||||||||
1. IntroductionWelcome to the MyEclipse JPA and Spring tutorial. In this tutorial we are going to take a look at some of the new JPA-Spring based features in the MyEclipse 6.0 release and beyond. 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 new JPA-Spring integration in MyEclipse 6.0 and how to utilize that new functionality. |
||||||||||||
2. Suggested AudienceThis 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 6.0. If you are using a
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 StartedGetting started with JPA and Spring in MyEclipse begins with two things:
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...:
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:
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):
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:
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 EngineeringNow 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. New in MyEclipse 6.0, we no longer have to switch back to the DB Explorer Perspective to reverse-engineer, we can do it directly from the project. In our case 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...:
After selecting the table to reverse-engineer and hitting next
you will be prompted to select how you want the entities and DAOs
generated:
When the reverse-engineering dialog comes up you will want to fill out the following fields:
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:
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:
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:
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 EntityThe 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:
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
|
/* 1. Now retrieve the new product line,
using the ID we created */
|
| 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.
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 */
|
| 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.
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 */
|
| 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.
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.
|
|
Figure 16. Turning on support for the @Transactional annotation
|
|
|
Figure 17. Annotation driven configuration element
|
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 |
JPAServiceBean bean = (JPAServiceBean) ctx.getBean("JPAServiceBean");
bean.deleteProductLine(productlineID);
|
| Figure 19. Using JPAServiceBean |
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.
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.
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.